首页 > 解决方案 > C++/CLI 获取“包装器”类对象以显示在 C# 中

问题描述

我有这个教程工作:https ://www.red-gate.com/simple-talk/dotnet/net-development/creating-ccli-wrapper/

该教程在一个解决方案中使用了 3 个 Visual Studio 项目。“核心”项目是本机 C++ 端。“Wrapper”项目是 C++/CLI “桥梁”。而“沙盒”项目是 C# 端。

现在我正在尝试修改它以使用我添加到核心的 C++ 函数,但是我的新 Wrapper 方法和属性没有显示在 C# 中。我的最终目标是 C# 应用程序将文本发送到 C++ 程序,然后 C++ 程序查询数据库,并返回与文本匹配的前 20 条记录。现在,我只想向 C++ 类发送一个字符串和一个整数,并让它返回一个重复整数次的字符串向量。

我希望我能够在 Wrapper 中创建一个新属性,并且它会显示在 C# 中。我的属性指向 Core 中的一个函数,工作属性/函数与失败的属性/函数之间的唯一显着区别是正在使用的类型。在 Wrapper 项目头文件中,我添加了这样的函数:

void TypeAhead( std::string words, int count );

在 Wrapper .cpp 文件中,我添加了以下内容:

void Entity::TypeAhead( std::string words, int count )
{
    Console::WriteLine( "The Wrapper is trying to call TypeAhead()!" );
    m_Instance->TypeAhead( words, count );
}

我在核心项目中有匹配的功能。在 Program.cs 中,Entity 类对象能够使用教程中的属性和函数,但不能使用我添加的那些。我需要更改哪些内容才能从 Wrapper 项目中获取属性和函数才能在 Sandbox 项目中使用?

我的仓库可以在这里找到:https ://github.com/AdamJHowell/CLIExample

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

解决方案


问题是std::string在尝试向 .NET 公开时它不是有效类型。它是一个纯粹的 c++ 野兽。

改变:

void Entity::TypeAhead( std::string words, int count )
{
    Console::WriteLine( "The Wrapper is trying to call TypeAhead()!" );
    m_Instance->TypeAhead( words, count );
}

...到:

void Entity::TypeAhead( String^ words, int count )
{
    Console::WriteLine( "The Wrapper is trying to call TypeAhead()!" );

    // use your favourite technique to convert to std:string, this 
    // will be a lossy conversion.  Consider using std::wstring.
    std::string converted = // ...
    m_Instance->TypeAhead(converted, count );
}

在内部使用 std::wstring 代替

正如下面 Tom 的精彩评论所表明的那样,wstring由于在从 .NET 字符串到std::string. 要转换,请参阅下面的链接。


推荐阅读