在 C++ 中,我有一些代码需要传入 const char *
:
void Load(const char *filename)
如果我按照 MSDN 的建议尝试使用 String
:
[DllImport("foo.dll")]
protected static extern void Load(String filename);
由于托管 P/Invoke 调用与实际 C++ 函数签名之间的不匹配,我最终收到一个异常,指出该调用具有不平衡的堆栈。
我需要使用什么合适的 C# 函数签名?我已尝试通过谷歌搜索寻找答案,但我什么也没想到。
解决方案: 事实证明,我收到“堆栈不平衡”错误的原因是因为我正在运行的测试代码调用了目录中实际上不存在的文件.通过 CallingConvention=cdecl
和适当位置的文件,问题得到解决。
最佳答案
问题是调用约定。当我们这样做时,您可能需要指定字符集,因为否则它可能会采用 Unicode:
[DllImport("foo.dll", CharSet:=CharSet.Ansi, CallingConvention:=CallingConvention.Cdecl)]
protected static extern void Load(String filename);
关于c# - 我应该如何为这段代码指定 P/invoke 接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7683242/