【问题标题】:Import C++ DLL in C#, function parameters在C#中导入C++ DLL,函数参数
【发布时间】:2013-12-21 00:17:07
【问题描述】:

我正在尝试在 C# 中导入我的 C++ Dll。它似乎适用于没有参数的函数,但我的函数有一些问题。

我的 C++ 函数:

__declspec(dllexport) bool SetValue(const std::string& strV, bool bUpload)
{ 
    return ::MyClass::SetValue(strV.c_str(), bUpload);              
}

它被包裹在"ex​​tern "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 的视图以查看显示“未定义值”的值时”。

也许有人知道我的代码有什么问题?

谢谢!

【问题讨论】:

  • C# 不知道std::string 是什么。您需要导出采用原始字符指针的函数版本。

标签: c# c++ string pinvoke


【解决方案1】:

您不能希望使用pinvoke 传递std::stringstd::string 是一个只能在 C++ 代码中使用的 C++ 类。

您的选择:

  1. 编写 C++/CLI 包装器。
  2. 使用互操作友好类型,例如 const char*BSTR

您手头似乎已经有一个接受const char* 的函数版本。你可以很容易地 p/invoke 。

[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# bool 编组时,C++ bool 是否也需要注解?
  • 谢谢!我已经用 const char * 替换了我的 std::string 并且我的 C# 看起来像你的。但是,当我尝试在调试模式下读取值时,它是“V”而不是“VALUE”,只有第一个字母。
  • 听起来您正在发送 UTF16。您使用的是什么操作系统?
  • 不管怎样,加个 MarshalAs 显式,或者在 DllImport 属性中设置 CharSet
  • 我在 W7 x64 上。字符集现在处于“自动”状态。我必须使用什么 MarshalAs ?
【解决方案2】:

我不确定,但你应该改用 StringBuilder 试试这个:

[DllImport("MyDll.dll", EntryPoint = "SetValue", CharSet = CharSet.Auto, SetLastError = true, CallingConvention = CallingConvention.Cdecl)]
    public static extern void SetValue(StringBuilder strVal, bool bUpload);

【讨论】:

  • 不是const char*参数。
猜你喜欢
  • 2016-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多