1

我的 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# 应用程序调用。调用时,它会生成访问冲突异常。

经过研究,我发现了我的问题的原因。

http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/6e843243-baf4-4eb1-8a20-c691ad47762c

但无法理解他们在示例代码中到底在做什么。有人可以解释一下吗?

在外部分配内存后,c# 中的 P/Invoke 签名是什么?

4

2 回答 2

0

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
于 2010-03-08T16:22:43.360 回答
0

我将 O_len 的传递模式更改为out而不是ref并且它可以工作。

感谢大家给出很好的答案和评论。我希望这对其他社区成员有用(加上那些谷歌搜索......)

于 2010-03-13T08:32:42.070 回答