DLLImport a variable MFC dll

风格不统一 提交于 2020-01-06 15:40:22

问题


So I created the following test project:

[DllImportAttribute("TestMFCDLL.dll", CallingConvention = CallingConvention.Cdecl)]
internal static extern int test(int number);

private void button1_Click(object sender, EventArgs e)
{
    int x = test(5);
}

Which works fine for my MFC dll that has the function test defined, however what I actually have is many MFC dlls that all share a common entry function and run differently based on my inputs. So basically I have tons of dlls that I cannot know at compile time what the name is, I just know that they have a function similar to how this program is setup, is there a way to import a dll based on run-time knowledge? Simply doing this returns an error:

static string myDLLName = "TestMFCDLL.dll";
[DllImportAttribute(myDLLName, CallingConvention = CallingConvention.Cdecl)]

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type


回答1:


If you want to dynamically load a DLL and use the functions in the DLL, then you'll need to do a little bit more. First you need to load the DLL dynamically. You can use LoadLibrary and FreeLibrary for that.

[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary(string dllName);

[DllImport("kernel32.dll")]
public static extern bool FreeLibrary(IntPtr hModule);

Second you need to get the address of the function in the DLL and call it.

[DllImport("kernel32.dll")]
public static extern IntPtr GetProcAddress(IntPtr hModule, string functionName);

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int Test(int number);

Putting that all together:

IntPtr pLib = LoadLibrary(@"PathToYourDll.DLL");
IntPtr pAddress = GetProcAddress(pLib, "test");
Test test = (Test)Marshal.GetDelegateForFunctionPointer(pAddress, typeof(Test));
int iRresult = test(0);
bool bResult = FreeLibrary(pLib);


来源:https://stackoverflow.com/questions/14628211/dllimport-a-variable-mfc-dll

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!