从C+调用C#函数+/CLI-将返回的C#字符串转换为C字符串

从C+调用C#函数+/CLI-将返回的C#字符串转换为C字符串,c#,c++-cli,C#,C++ Cli,我有一个C#函数,我把它做成了一个DLL: public static string Test(string name) { return "Hello " + name; } 在C++/CLI项目中,我成功导入了DLL,现在我想有一种方法调用该函数,使它可以用于正常的非托管C++。因此,我想像这样导出C++/CLI函数: extern "C" __declspec(dllexport) void __stdcall Example(char* name, char* greet) {

我有一个C#函数,我把它做成了一个DLL:

public static string Test(string name)
{
    return "Hello " + name;
}
<>在C++/CLI项目中,我成功导入了DLL,现在我想有一种方法调用该函数,使它可以用于正常的非托管C++。因此,我想像这样导出C++/CLI函数:

extern "C" __declspec(dllexport)
void __stdcall Example(char* name, char* greet) {
    // name will be passed to C# Test(...) function
    // and greet will contains the returned value

    // call to the C# function here:
    ...
}
void __stdcall Example(char* name, char* greet, size_t destBufferSize)
<>我不在乎C++ +CLI函数的外观,只要我可以将它导出到普通的非托管C++。< /P> **编辑:当有人抱怨我的问题时,我只需要知道在给定C字符串的情况下如何调用C#函数,以及如何检索返回的结果并将其存储在另一个C字符串中。这不像是一个“问题”,它就像一个不知道如何编码的新手,来这里问。。。多谢各位**


**编辑2:现在我注意到,有人编辑了我的帖子(我不知道,是版主还是其他人…)。现在当我重新阅读我的帖子时,我甚至不知道这篇帖子想问什么。。。拜托,我认为你不应该那样做**

使用C++/CLI,你有你所需要的一切

你可以这样做:

#include <string>
#include <msclr\marshal_cppstd.h>

extern "C" __declspec(dllexport)
void __stdcall Example(char* name, char* greet) {
    // name will be passed to C# Test(...) function
    // and greet will contains the returned value

    // Create new System::String^ from char*
    System::String^ clrString = msclr::interop::marshal_as<System::String^>(name);

    // Call C# function
    System::String^ result = Test(clrString);

    // Create new std::string from System::String^
    std::string cppString = msclr::interop::marshal_as<std::string>(result);

    // Copy C++-string to the destination
    strcpy(greet, cppString.c_str());
}
或者更进一步,因为
System::String
有一个接受
char*
的构造函数:

strcpy(greet, marshal_as<string>(Test(name)).c_str());

并使用
strncpy
或类似方法检查destBufferSize是否足够大以包含结果字符串或截断值

这可能会有所帮助,谢谢,我已经看过了,但我想要的是调用一个以字符串为参数的C#函数,它将返回C#字符串,所以我想知道如何检索它并转换为C字符串。也许我的问题有点不清楚,这根本不是问题。这个示例非常糟糕,很难将一个C#字符串转换为两个C字符串,缓冲区溢出风险非常大,但C++/CLI为您提供了使其工作所需的所有工具。你必须更具体地说明你被卡住的地方。@HansPassant我根本不想把一个C#字符串变成两个C#字符串,请在回答之前先阅读我的问题……编辑没问题,他只是删除了没有给问题添加任何有价值的部分。最后,成功了,你救了我一天!我花了一整天的时间来寻找这个,但运气不好!谢谢你!
void __stdcall Example(char* name, char* greet, size_t destBufferSize)