[英]Import C++ DLL in C#, function parameters
我正在尝试在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);
当我使用调试模式并输入SetValue(const char * sZvalue,bool bUpload)函数时,sZvalue为“ 0x4552494F”,但是当我尝试扩展Visual Studio的视图以查看该值时,它显示为“未定义值”。
也许有人对我的代码有什么想法?
谢谢 !
您不能希望使用pinvoke
传递std::string
。 std::string
是一个C ++类,只能在C ++代码中使用。
您的选择:
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
。
我不确定,但是您应该使用StringBuilder尝试以下操作:
[DllImport("MyDll.dll", EntryPoint = "SetValue", CharSet = CharSet.Auto, SetLastError = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void SetValue(StringBuilder strVal, bool bUpload);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.