C ++ / CLI让“包装”类对象显示在C#中

问题描述 投票:1回答:2

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

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

现在我试图修改它以使用我添加到Core的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 );
}

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

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

c# c++ c++-cli
2个回答
1
投票

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


0
投票

该函数签名与C#不兼容,因为它按值传递C ++本机类型。

你正在寻找的签名是

void TypeAhead( System::String^ words, int count );

在调用核心函数之前,您需要使用convert from the .NET String to a C++ std::string

© www.soinside.com 2019 - 2024. All rights reserved.