Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在C dll中调用方法失败_C#_Dllimport - Fatal编程技术网

C# 在C dll中调用方法失败

C# 在C dll中调用方法失败,c#,dllimport,C#,Dllimport,我尝试从C调用用C编写的dll方法 这是C方法: char *c_ata(char * const c, const size_t c_len, const unsigned char * const b, const size_t b_len); 我试着这样称呼它 [DllImport(EntryPoint = "c_ata", CallingConvention = CallingConvention.Cdecl)] private static extern string cAta(by

我尝试从C调用用C编写的dll方法

这是C方法:

char *c_ata(char * const c, const size_t c_len, const unsigned char * const b, const size_t b_len);
我试着这样称呼它

[DllImport(EntryPoint = "c_ata", CallingConvention = CallingConvention.Cdecl)]
private static extern string cAta(byte[] c, long c_len, byte[] b, long b_len);
问题是,当我尝试运行或调试NUnit测试时,我没有得到任何错误


我不太熟悉C语言的语法,所以问题是?我的调用语法理论上正确吗?

在C中,long指定一个64位整数。C代码中的大小是64位吗?如果不是,PInvoke签名应该更改为使用int而不是long


如果PInvoke签名声明为返回字符串,封送拆收器将从返回的指针创建一个字符串,然后对指针调用CoTaskMemFree。只有当指针最初是用CoTaskMemAlloc分配的时,这才合适。如果本机端自行清理内存,则应声明PInvoke返回一个IntPtr,然后您可以使用Marshal.PtrToStringAnsi或等效程序生成字符串。

大小参数需要为IntPtr。字符串返回值也必须是IntPtr,否则封送拆收器将尝试销毁该字符串。C代码很少使用CoTaskMemAlloc来分配可以在另一个模块中安全释放的内存。这很可能是一个可拔掉的内存泄漏。使用Marshal.PtrToStringAnsi转换IntPtr。编写一个调用该函数数百万次的测试程序,观察内存使用情况。