我有一个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:
...
}
我不关心C ++ / CLI函数的样子,只要我可以将它导出到普通的非托管C ++。
**编辑:当有人抱怨我的问题时,我只需要知道如何在给定C字符串的情况下调用C#函数,以及如何检索返回的结果并将其存储在另一个C字符串中。这不像是一个“问题”,它就像一个不知道如何编码的新手,来这里问......谢谢你**
** Edit2:现在我注意到,有人编辑了我的帖子(我不知道,是主持人还是其他人......)。现在,当我重新阅读我的帖子时,即使我不知道帖子试图问什么...请,我认为你不应该这样做**
答案 0 :(得分:1)
使用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());
}
此解决方案使用std::string
。您还可以使用marshal_context
直接在System::String
和char[]
之间进行转换,但我更喜欢使用std::string
,因为它可以为您节省一些打字费用,并且可以减少错误。
当然,可以将其缩短为:
strcpy(greet, marshal_as<string>(Test(marshal_as<String^>(name))).c_str());
或者更进一步,因为System::String
有一个构造函数接受char*
:
strcpy(greet, marshal_as<string>(Test(name)).c_str());
请点击此处了解有关编组的更多信息:http://msdn.microsoft.com/en-us/library/bb384865.aspx
重要的:
C#使用动态字符串,C#代码通常很乐意生成非常长的字符串,如果greet
指向的内存不足以包含字符串,则会导致崩溃或更糟。
处理此问题的常用方法是将Example
的签名更改为以下内容:
void __stdcall Example(char* name, char* greet, size_t destBufferSize)
检查destBufferSize是否足够大以包含结果字符串或使用strncpy
或类似方法截断值。