将字符串从 C++/CLI class 库传递到 C#
passing string from C++/CLI class library to C#
我在 VS 2010 C++/CLI 中编写了一个 class 库并创建了一个 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();
...
这个问题我该怎么办?
对于互操作方案,您需要 return 一个字符串 object 您将能够从 .NET 代码中读取。
不要 return std::string
(C# 中没有这样的东西)或 const char *
(可从 C# 读取,但您必须管理内存释放)或像这样的东西。 Return 改为 System::String^
。这是 .NET 代码中的标准字符串类型。
这会起作用:
public: System::String^ getStringFromCpp()
{
return "Hello World";
}
但如果您确实有 const char *
或 std::string
object,则必须使用 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
模板,如上文 link 所述。您只需要包含一个不同的 header:
#include <msclr/marshal_cppstd.h>
System::String^ cliStr = "Hello, World!";
std::string stdStr = msclr::interop::marshal_as<std::string>(cliStr);
在我的程序中它以某种方式拒绝将 std::string 直接转换为 System::String^ 但采用 char* 转换 ==> std::string.c_str()
public: System::String^ getStringFromCpp()
{
std::string str = "Hello World";
return msclr::interop::marshal_as<System::String^>(str.c_str());
}
我在 VS 2010 C++/CLI 中编写了一个 class 库并创建了一个 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();
...
这个问题我该怎么办?
对于互操作方案,您需要 return 一个字符串 object 您将能够从 .NET 代码中读取。
不要 return std::string
(C# 中没有这样的东西)或 const char *
(可从 C# 读取,但您必须管理内存释放)或像这样的东西。 Return 改为 System::String^
。这是 .NET 代码中的标准字符串类型。
这会起作用:
public: System::String^ getStringFromCpp()
{
return "Hello World";
}
但如果您确实有 const char *
或 std::string
object,则必须使用 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
模板,如上文 link 所述。您只需要包含一个不同的 header:
#include <msclr/marshal_cppstd.h>
System::String^ cliStr = "Hello, World!";
std::string stdStr = msclr::interop::marshal_as<std::string>(cliStr);
在我的程序中它以某种方式拒绝将 std::string 直接转换为 System::String^ 但采用 char* 转换 ==> std::string.c_str()
public: System::String^ getStringFromCpp()
{
std::string str = "Hello World";
return msclr::interop::marshal_as<System::String^>(str.c_str());
}