DLL导入变量MFC dll [英] DLLImport a variable MFC dll

查看:74
本文介绍了DLL导入变量MFC dll的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我创建了以下测试项目:

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);
}

对于定义了功能测试的MFC dll,哪一个工作正常,但是实际上我拥有的许多MFC dll都共享一个公用的输入函数,并根据我的输入以不同的方式运行.所以基本上我有成堆的dll,在编译时我不知道名字是什么,我只知道它们具有类似于此程​​序的设置功能,是否可以基于运行时知识导入dll?简单地执行此操作将返回错误:

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)]

属性参数必须是常量表达式,typeof表达式 参数类型的数组或数组创建表达式

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

推荐答案

如果要动态加载DLL并使用DLL中的函数,则需要做更多的事情.首先,您需要动态加载DLL.您可以为此使用LoadLibrary和FreeLibrary.

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);

第二,您需要在DLL中获取函数的地址并调用它.

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);

将它们放在一起:

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);

这篇关于DLL导入变量MFC dll的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆