我应该如何为这段代码指定P/invoke接口?

发布于 2024-12-08 18:04:55 字数 511 浏览 3 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

转角预定愛 2024-12-15 18:04:55

问题在于调用约定。当我们这样做时,您可能需要指定字符集,因为否则它可能会假设 Unicode:

[DllImport("foo.dll", CharSet:=CharSet.Ansi, CallingConvention:=CallingConvention.Cdecl)]
protected static extern void Load(String filename);

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:

[DllImport("foo.dll", CharSet:=CharSet.Ansi, CallingConvention:=CallingConvention.Cdecl)]
protected static extern void Load(String filename);
感受沵的脚步 2024-12-15 18:04:55

您可以添加 MarshalAsAttribute< /a> 就像例如

[DllImport("foo.dll")]
protected static extern void Load(
    [MarshalAs(UnmanagedType.LPStr)]string filename);

您可以传递 UnmanagedType 枚举 值传递给 MarshalAsAttribute 构造函数。

另请参阅代码项目上的这篇概述文章

You could add the MarshalAsAttribute like e.g.

[DllImport("foo.dll")]
protected static extern void Load(
    [MarshalAs(UnmanagedType.LPStr)]string filename);

You can pass one of the UnmanagedType enumeration values to the MarshalAsAttribute constructor.

See also this overview article over at Code Project.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文