我应该如何为这段代码指定P/invoke接口?
在 C++ 中,我有一些代码需要传入 const char *
:
void Load(const char *filename)
如果我尝试使用 String
正如 MSDN 似乎建议的那样:
[DllImport("foo.dll")]
protected static extern void Load(String filename);
我最终得到一个异常,指出由于托管 P/Invoke 调用与实际 C++ 函数签名之间不匹配,该调用的堆栈不平衡。
我需要使用什么合适的 C# 函数签名?我尝试用谷歌搜索答案,但没有找到任何答案。
解决方案:事实证明,我收到“不平衡堆栈”错误的原因是因为我运行的测试代码调用了目录中实际不存在的文件。使用 CallingConvention=cdecl 并将文件放在适当的位置,问题就得到了解决。
In C++ I have some code that requires a const char *
to be passed in:
void Load(const char *filename)
If I try using String
as MSDN seems to suggest:
[DllImport("foo.dll")]
protected static extern void Load(String filename);
I end up getting an exception stating that the call has an unbalanced stack, due to a mismatch between the managed P/Invoke call and the actual C++ function signature.
What would be the appropriate C# function signature I would need to use? I've tried googling for the answer but I'm not coming up with anything.
The solution: It turns out that the reason why I was getting an "unbalanced stack" error was because the test code I was running called for a file that didn't actually exist in the directory. With CallingConvention=cdecl
, and the file in the appropriate place, the issue was resolved.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题在于调用约定。当我们这样做时,您可能需要指定字符集,因为否则它可能会假设 Unicode:
The problem is the calling convention. And while we're at it, you probably need to specify the character set since it may assume Unicode otherwise:
您可以添加
MarshalAsAttribute
< /a> 就像例如您可以传递
UnmanagedType
枚举 值传递给MarshalAsAttribute
构造函数。另请参阅代码项目上的这篇概述文章。
You could add the
MarshalAsAttribute
like e.g.You can pass one of the
UnmanagedType
enumeration values to theMarshalAsAttribute
constructor.See also this overview article over at Code Project.