【发布时间】:2017-10-31 15:07:44
【问题描述】:
我正在尝试在我的 C# 程序中使用我的 C++ 类。所以我制作了一个 .dll 文件以在 C# 中使用它。我的问题是,我正在使用字符串。我的问题是:如何将 std::string 返回到我的 C# 程序?
我的 C++ 类(头文件):
using namespace std;
class CComPort
{
public:
string ReadLine();
void WriteLine(string userInput);
};
我的 dll 代码:
string CppWrapper::CComPortWrapper::ReadLineWrapper()
{
return comPort->ReadLine();
}
void CppWrapper::CComPortWrapper::WriteLineWrapper(string userInput)
{
comPort->WriteLine(userInput);
}
我的 C#-代码:
comPort.WriteLineWrapper(tb_send.Text);
错误:
'CComPortWrapper.WriteLineWrapper(?,?)' is not supported by the language.
我尝试将 dll 文件更改为类似的内容,但没有成功:
void CppWrapper::CComPortWrapper::WriteLineWrapper(String ^ userInput)
{
comPort->WriteLine(userInput);
}
改变它的正确方法是什么?
【问题讨论】:
-
std::string in C#?的可能重复
-
std::string 不受 C# 语言支持。我们无法判断您的 ComPort::WriteLine() 函数需要什么类型,但 Marshal::StringToHGlobalAnsi() 往往适合。不要忘记 Marshal::FreeHGlobal()。注意确切的编码也没有什么坏处,考虑将其声明为
void WriteLine(array<Byte>^ buffer);并使用pin_ptr以便 C# 代码可以使用 Encoding 类正确处理。