最近在项目中碰到需要调用非托管C++生成的dll,下面将自己遇到的问题,以及解决的办法总结如下:
1.
问题:
我们通常去映射dll的方法是使用
解决方案:
[DllImport(
"
Kernel32.dll
"
)]
public
static
extern
IntPtr LoadLibrary(
string
lpFileName);
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
[DllImport(
"
kernel32.dll
"
, SetLastError
=
true
)]
public
static
extern
int
GetProcAddress(
IntPtr hModule,
string
1.
问题:
我们通常去映射dll的方法是使用
public
const
string
dllPath
=
path;
[DllImport(dllPath + " test.dll " , EntryPoint = " test() " , SetLastError = true ,
CharSet = CharSet.Ansi, ExactSpelling = true , CallingConvention = CallingConvention.Cdecl)]
public static extern int test();
这种方式有一个致命的缺陷,dll文件路径dllPath必须为const,而const是编译时常量,也就是说dllPath赋值必须是字符串常量,如果你想动态指定dll文件路径用这种方式基本上没办法实现,下面是一种解决方案。[DllImport(dllPath + " test.dll " , EntryPoint = " test() " , SetLastError = true ,
CharSet = CharSet.Ansi, ExactSpelling = true , CallingConvention = CallingConvention.Cdecl)]
public static extern int test();
解决方案:
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)