【问题标题】:passing string from C++/CLI class library to C#将字符串从 C++/CLI 类库传递到 C#
【发布时间】:2015-09-01 04:51:29
【问题描述】:

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

我应该如何处理这个问题?

【问题讨论】:

  • 我无法理解 c++ 到 c# 的方向,c++ foo 函数返回 void?我如何在 c# 中给出这个字符串?
  • 你在说什么?什么foo()?除此之外,您上面的代码有什么问题?看起来应该可以工作
  • 你能用示例“hello world”解释它并在c#的文本框中使用它吗?
  • 问题是你不理解上面的代码,而不是里面可能有bug

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


【解决方案1】:

对于互操作场景,您需要返回一个可以从 .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);

【讨论】:

  • 哇,终于可以正常使用了。非常非常非常感谢亲爱的卢卡斯。你能解释一下其他方向吗?从 c# 发送一个字符串并将其用作 c++ 中的 std:string?
  • @user3778594 我将其添加到答案中
  • 我参与了这个问题 2 天,感谢您。
【解决方案2】:

在我的程序中,它以某种方式拒绝将 std::string 直接转换为 System::String^ 但采用 char* cast ==> std::string.c_str()

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-12
    • 2015-12-23
    • 2014-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多