我正在尝试在 C# 中导入我的 C++ Dll。它似乎适用于没有参数的函数,但我的函数有一些问题。
我的 C++ 函数:
__declspec(dllexport) bool SetValue(const std::string& strV, bool bUpload)
{
return ::MyClass::SetValue(strV.c_str(), bUpload);
}
它被包裹在“extern "C"{”
该函数调用另一个函数:
bool SetValue(const char* szValue, bool bUpload)
{
}
我的 C# 函数:
[DllImport("MyDll.dll", EntryPoint = "SetValue", CharSet = CharSet.Auto, SetLastError = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void SetValue([MarshalAs(UnmanagedType.LPStr)]string strVal, bool bUpload);
当我使用 Debug模式并输入 SetValue(const char* sZvalue, bool bUpload) 函数时,sZvalue 为“0x4552494F”,但是当我尝试展开 Visual Studio 的 View 以查看该值时,它显示“未定义值” ”。
也许有人知道我的代码出了什么问题?
谢谢!
最佳答案
您不能希望使用 pinvoke
传递 std::string
。 std::string
是一个只能在 C++ 代码中使用的 C++ 类。
您的选择:
- 编写 C++/CLI 包装器。
- 使用互操作友好的类型,例如
const char*
或BSTR
。
您似乎已经拥有接受 const char*
的函数版本。你可以很容易地p/调用它。
[DllImport("MyDll.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void SetValue(
string strVal,
[MarshalAs(UnmanagedType.I1)]
bool bUpload
);
显然,您需要导出接受 const char*
的 SetValue
版本。
请注意,您不应在此处使用 SetLastError
,除非您的 API 确实调用了 SetLastError
。如果确实如此,那将是不寻常的。通常是 Win32 API 函数来执行此操作。
正如 @Will 指出的,您应该使用 MarshalAs
告诉编码器 bool
参数将被编码为单字节 C++ bool
而不是默认的 4 字节 Windows BOOL
。
关于c# - 在C#中导入C++ DLL,函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20376592/