当前位置: 代码迷 >> C# >> C#调用C语言的DLL解决思路
  详细解决方案

C#调用C语言的DLL解决思路

热度:96   发布时间:2016-05-05 04:48:45.0
C#调用C语言的DLL
C#调用C语言实现的DLL时,出现CoTaskMemFree(IntPtr ptr ) 的错误,查了一下,感觉是参数没有对应上,哪位大侠帮我看看是哪里的问题好吗,跪谢~

C语言被调用代码:
test.dll
__declspec(dllexport) char* fun(DWORD mode,const char* password);
char* fun( DWORD mode, const char* password);

C#调用侧代码:
        static String code;
        [DllImport("test.dll", CharSet = CharSet.Ansi)]
        public static extern String fun(int mode, String password);

        static void Main(string[] args)
        {
            String s = "123";
            code = obl_crypto_hash(5, s);
        }
------解决思路----------------------
DWORD=double word
你应该使用long型,而不是int型
------解决思路----------------------
引用:
DWORD=double word
你应该使用long型,而不是int型


double word表示2个字,即4字节,32位,
C#中int就是32位,而long在C#中表示64位
------解决思路----------------------
默认c使用__cdecl的调用约定,需要DllImport里面设置CallingConvention属性为CallingConvention.Cdecl。

返回char *当作string的话,.net会认为它应该是通过CoTaskMemAlloc分配的,并且应该由.net释放。你看到的错误就是试图释放这个内存时产生的。所以如果要返回不是CoTaskMemAlloc分配的的或者不希望释放的char *,那么应该使用IntPtr作为返回类型,然后使用 Marshal.PtrToStringAnsi (如果确定使用ansi方式) 来转换成string。
  相关解决方案