c# - 使用整数指针从 C# 调用外部 DLL

标签 c# c++ dll interop

我正在尝试从 C# 调用外部 .dll 函数。 dll 的文档定义了函数:

int funcName(int *retVal)

我尝试了各种配置,但总是出现来自 p/invoke 的不平衡堆栈错误;我的 C# 代码目前看起来像这样:

[DLLImport("dllName");
unsafe static extern int funcName(ref IntPtr retVal);
unsafe IntPtr retNum;
int status = funcName(ref retNum);

欢迎任何想法!

最佳答案

你的 p/invoke 声明有错误的参数类型。

  • ref Int32int* 的正确匹配。

  • IntPtr 也可以。

  • ref IntPtr 将是 int**。绝对不是你想要的。

使用

[DLLImport("dllName")]
static extern int funcName(ref Int32 retVal);

还要确保调用约定匹配。在不使用显式调用约定的情况下,切勿在 C 或 C++ 中使用 dllexport,然后 C# DllImport 需要具有匹配的约定。

一般C++中的原型(prototype)应该是

extern "C" int __stdcall funcName(int* arg);

是否为 C 和 C++ 客户端提供了一个头文件,您可以检查以验证签名?

关于c# - 使用整数指针从 C# 调用外部 DLL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23325668/

相关文章:

c# - Entity Framework 查询生成器方法 : why "it" and not lambdas?

c++ - 如何将 DLL 链接到我的主项目? (获取 Unresolved external 错误)

c# - Clr dll .net 控件

linux - 在 Linux/Unix 中转发 DLL 的等价物是什么?

c# - 如何使用 C# 以编程方式检查 jre 环境是 32 位还是 64 位?

c# - Word Interop Delete 导致参数错误

c# - WPF:从目录加载图像并将其列在 WrapPanel 中

c++ - 使标准控制台出现在快板中

android - 我正在尝试编译我的 jnicode,它显示错误 _JNIEnv::GetShortArrayElements(JNIEnv*&, _jshortArray*&, int)'

C++11 模板函数 "implicity"将 bitset<N> 转换为 "unsigned long"