c# - 将字符串从 C++/CLI 类库传递到 C#

标签 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();
...

遇到这个问题我该怎么办?

最佳答案

对于互操作场景,您需要返回一个能够从 .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/

相关文章:

c# - 允许对象移动的 WPF 容器

c# - 表 __MigrationHistory 未更新

Java Scanner 类读取字符串

c# - 从 C# 类库导出函数

通过 nvidia quadro 600 gpu 模式访问时 C# DOT NET 应用程序崩溃 - nvd3dum.dll 崩溃

windows - 如果加载它的 DLL 被卸载,DLL 是否会被删除?

c# - WPF饼图如何在切片之间添加空间?

c# - Linq to Sql 内部连接

java - 从字符串中提取每个单词并比较频率

php - 在网站结构中找到 "orphan"文件