我对 C++ 编程完全陌生。我需要从 C# 调用 C++ 函数。
C++ 函数是:
BOOL Usb_Init(HWND hwnd);
我试过:
[DllImport("UsbComm.dll", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool Usb_Init( out IntPtr hwnd);
我收到错误信息:
PInvoke signature does not match the unmanaged target signature.
如何调用上面的C++方法?
最佳答案
我在问题的代码中看到以下错误:
- C++代码使用
cdecl
,C#代码使用stdcall
。那不匹配。 - C++ 代码通过值传递一个
HWND
。 C# 代码有一个作为out
参数传递的IntPtr
。那不匹配。 DllImport
属性有多个虚假参数。
正确的 C# 声明是:
[DllImport("UsbComm.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern bool Usb_Init(IntPtr hwnd);
您可以将 ExactSpelling
设置为 true
但我认为没有令人信服的理由这样做。如果您愿意,请随时添加。指定 CharSet
没有意义,因为不涉及文本。 SetLastError = true
可能是一个错误。根据我的判断,非托管函数不太可能调用 SetLastError
。我的期望是您在尝试消除错误时添加了 SetLastError = true
。
关于c# - C++ 函数到 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28291944/