C++调用dll函数时发生访问冲突
我的 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 签名是什么?
I have a function definition in my 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);
}
This dll function is called by a c# application.
When called, it generate access violation exception.
After reasearching i found, the cause for my problem.
But could not understand what exactly they are doinng in example code.
Can someone explain it so me?
And what would be P/Invoke signature in c# after externally allocating memory?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
C# 使用 IntPtr 来表示外部分配的内存。 C# 指针和引用只能与垃圾收集器提供的内存一起使用。
System.InteropServices.Marshal 类提供了一些与 IntPtr 表示的本机内存区域进行交互的方法,当然它们不是类型安全的。
但我在你的函数中没有看到任何可以返回指向已分配内存的指针的内容。您需要一个双指针参数或一个指针返回值,但两者都没有。
编辑以根据要求添加示例:
更好:
C# uses IntPtr to represent externally allocated memory. C# pointers and references can only be used with memory provided by the garbage collector.
The System.InteropServices.Marshal class provides some methods for interacting with native memory areas represented by IntPtr, of course they aren't typesafe.
But I don't see anything in your function that could return a pointer to allocated memory. You'd need a double-pointer argument, or a pointer return value, and you have neither.
EDIT to add example as requested:
better:
我将 O_len 的传递模式更改为 out 而不是 ref 并且它有效。
感谢大家给出很好的答案和评论。我希望这对其他社区成员有用(加上那些谷歌搜索......)
I changed passing mode of O_len to out instead of ref and it works.
Thnaks everyone for giving nice answers and comments. I hope this would be useful for other community members ( plus those googling...)