有两种办法在C#中调用C++写的DLL的方法有两种:
1、COM
将C++代码封装成COM,然后在C#中引用
2、API
将C++代码封装成C接口的函数,类似于Windows的API,然后在C#中通过DllImport引用
例如:
c++头文件为
int _stdcall Decrypt(unsignec char *src, unsigned long src_len, unsigned char **dst, unsigned long *dst_len);
注:在*.def文件中需呀为定义Decrypt的导出
在c#中引用如下命名空章
using System.Runtime.InteropServices;
在某个类的构造函数后面添加:
[DllImport("CryptTools.dll")]
internal static extern int Decrypt(System.IntPtr src, int src_len, ref System.IntPtr dst, ref int dst_len);
添加函数封装对该API的调用:
internal static int Sharp_Decrypt(byte[] src, ref byte[] dst)
{
int result = -1, dstLen = 0;
IntPtr pSrc = Marshal.AllocHGlobal(src.Length);
Marshal.Copy(src, 0, pSrc, src.Length);
IntPtr pDst = IntPtr.Zero;
result = Decypt(pSrc, src.Length, ref pDst, ref dstLen);
if (0 == result)
{
dst = new byte[dstLen];
Marshal.Copy(pDst, dst, 0, dstLen);
}
Marshal.FreeHGlobal(pSrc);
return result;
}
请注意,出于篇幅的考虑,此处没有在CryptTools.dll中添加unsigned char**的释放函数,需要读者自行添加。