将字符串从C ++ / CLI类库传递给C#

时间:2015-09-01 04:51:29

标签: c# string dll c++-cli

我在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();
...

我应该怎么处理这个问题?

2 个答案:

答案 0 :(得分:3)

对于互操作方案,您需要返回一个您能够从.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模板,如上面的链接所述。您只需要包含一个不同的标题:

#include <msclr/marshal_cppstd.h>
System::String^ cliStr = "Hello, World!";
std::string stdStr = msclr::interop::marshal_as<std::string>(cliStr);

答案 1 :(得分:0)

在我的程序中以某种方式它拒绝将std :: string直接转换为System :: String ^但是接受char * casting ==&gt;的std :: string.c_str()

public: System::String^ getStringFromCpp()
{
    std::string str = "Hello World";
    return msclr::interop::marshal_as<System::String^>(str.c_str());
}