c# - C++/CLI 获取 "wrapper"类对象以显示在 C# 中

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

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

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

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

我希望我能够在 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

最佳答案

问题是 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 的转换中可能会出现保真度损失。要转换,请参阅下面的链接。

关于c# - C++/CLI 获取 "wrapper"类对象以显示在 C# 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55203695/

相关文章:

c# - 从同一解决方案中的不同测试项目引用项目中的 C# 命名空间

c# - ICorProfiler : Why do I get the wrong type token for a jitted function?

c++ - "A matching symbol file was not found in this folder "。当我尝试使用转储文件进行调试时出现此错误

c++ - 在 c/c++ 中创建时间戳的可移植方式

c++11 - 安全地将回调从托管代码传递到 native 代码

c# - 使用/clr 编译现有的 C++ 代码,然后从 C# 调用它

.net - C++/CLI : Catching all (. NET/Win32/CRT) 异常

c# - 谷歌授权错误错误400 : redirect_uri_mismatch

c# - 使 DataGridView 在使用基类对象列表时显示派生类对象的属性

c++ - 使用鼠标选择轮廓?