我有一个C#应用程序需要从C ++ dll导入一个函数。我使用DLLImport加载该函数。它在英文和中文环境中工作正常,但它总是在法语操作系统中引发“模块未找到”异常。
代码快照:
[DllImport("abcdef.dll", CallingConvention = CallingConvention.StdCall)]
public static extern string Version();
请注意,模块名称中的字母已被替换,但名称本身的格式和长度相同。
截图:
有什么想法吗?
答案 0 :(得分:0)
我已尝试过您提出的所有方法,但问题仍然存在。
这是一种可以避免该错误的替代方法。它使用Win32 API加载库并查找函数的地址,然后调用它。演示代码如下:
class Caller
{
[DllImport("kernel32.dll")]
private extern static IntPtr LoadLibrary(String path);
[DllImport("kernel32.dll")]
private extern static IntPtr GetProcAddress(IntPtr lib, String funcName);
[DllImport("kernel32.dll")]
private extern static bool FreeLibrary(IntPtr lib);
private IntPtr _hModule;
public Caller(string dllFile)
{
_hModule = LoadLibrary(dllFile);
}
~Caller()
{
FreeLibrary(_hModule);
}
delegate string VersionFun();
int main()
{
Caller caller = new Caller("abcdef.dll");
IntPtr hFun = GetProcAddress(_hModule, "Version");
VersionFun fun = Marshal.GetDelegateForFunctionPointer(hFun, typeof(VersionFun)) as VersionFun;
Console.WriteLine(fun());
return 0;
}
}