我在 VS 2010 C++/CLI 中编写了一个类库并创建了一个 dll。
// testclass.h
#pragma once
#include <string>
namespace test
{
public ref class testclass
{
public:
std::string getstringfromcpp()
{
return "Hello World";
}
};
}
我想在C#程序中使用它,然后添加这个dll来引用:
using test;
...
testclass obj = new testclass();
textbox1.text = obj.getstringfromcpp();
...
遇到这个问题我该怎么办?
最佳答案
对于互操作场景,您需要返回一个能够从 .NET 代码中读取的字符串对象。
不要返回 std::string
(C# 中没有这样的东西)或 const char *
(从 C# 可读,但你必须管理内存释放)或类似的事情。返回一个 System::String^
。这是 .NET 代码中的标准字符串类型。
这会起作用:
public: System::String^ getStringFromCpp()
{
return "Hello World";
}
但是,如果您实际上有一个 const char *
或 std::string
对象,则必须使用 marshal_as
模板:
#include <msclr/marshal.h>
public: System::String^ getStringFromCpp()
{
const char *str = "Hello World";
return msclr::interop::marshal_as<System::String^>(str);
}
阅读Overview of Marshaling in C++了解更多详情。
要将 System::String^
转换为 std::string
,您还可以使用 marshal_as
模板,如上面所述关联。您只需要包含一个不同的 header :
#include <msclr/marshal_cppstd.h>
System::String^ cliStr = "Hello, World!";
std::string stdStr = msclr::interop::marshal_as<std::string>(cliStr);
关于c# - 将字符串从 C++/CLI 类库传递到 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32323766/