[英]C++ Access violation when calling dll function
我在VC ++ Win32 DLL中有一个函数定义
DEMO2_API void ProcessData(char* i_buff, unsigned short i_len, char* o_buf,
unsigned *o_len, unsigned short *errorCode)
{
__describe (i_buff,&i_len,o_buf,o_len,errorCode);
}
此dll函数由ac#应用程序调用。 调用时,它将生成访问冲突异常。
经过研究,我发现了问题的原因。
但是无法理解示例代码中的确切含义。 有人可以这样解释吗?
在外部分配内存后,c#中的P / Invoke签名是什么?
C#使用IntPtr表示外部分配的内存。 C#指针和引用只能与垃圾收集器提供的内存一起使用。
System.InteropServices.Marshal类提供了一些与IntPtr表示的本机内存区域进行交互的方法,当然它们不是类型安全的。
但是我在您的函数中看不到任何可能返回指向已分配内存的指针的信息。 您将需要一个双指针参数或一个指针返回值,而您都没有。
编辑以根据要求添加示例:
// this doesn't work right
void external_alloc_and_fill(int n, int* result)
{
result = new int[n];
while (n-- > 0) { result[n] = n; }
}
extern external_alloc_and_fill(int n, int* result)
int a = 5;
fixed (int* p = &a) {
external_alloc_and_fill(17, p);
// p still points to a, a is still 5
}
更好:
// works fine
void external_alloc_and_fill2(int n, int** presult)
{
int* result = *presult = new int[n];
while (n-- > 0) { result[n] = n; }
}
extern external_alloc_and_fill2(int n, ref IntPtr result)
int a 5;
IntPtr p = &a;
external_alloc_and_fill2(17, ref p);
// a is still 5 but p is now pointing to the memory created by 'new'
// you'll have to use Marshal.Copy to read it though
我将O_len的传递模式更改为out,而不是ref ,它可以工作。
谢谢大家提供不错的答案和意见。 我希望这对其他社区成员(以及那些使用谷歌搜索功能的人)有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.