如何SWIG std :: string&到C#ref string

我正在尝试将带有std::string引用的C ++函数转换为C#。

我的API看起来像这样:

 void GetStringDemo(std::string& str); 

理想情况下,我希望从C#中看到类似的东西

 void GetStringDemoWrap(ref string); 

我知道我需要为此创建一个类型图,我尝试了一些使用std_string.i文件的东西,但我不认为我会在任何地方。 有没有人有任何例子。 我是Swig和C#的新手,所以我无法想出任何真实的想法。

为了以后有人在寻找这个,我为C#创建了这样的std_string.i。 似乎适合我。 请注意,我将ref更改为out,因为它在我的情况下更合适,但ref也可以正常工作。

我从.i文件中调用了%include“std_string.i”

 /* ----------------------------------------------------------------------------- * std_string_ref.i * * Typemaps for std::string& and const std::string& * These are mapped to a C# String and are passed around by reference * * ----------------------------------------------------------------------------- */ %{ #include  %} namespace std { %naturalvar string; class string; // string & %typemap(ctype) std::string & "char**" %typemap(imtype) std::string & "/*imtype*/ out string" %typemap(cstype) std::string & "/*cstype*/ out string" //C++ %typemap(in, canthrow=1) std::string & %{ //typemap in std::string temp; $1 = &temp; %} //C++ %typemap(argout) std::string & %{ //Typemap argout in c++ file. //This will convert c++ string to c# string *$input = SWIG_csharp_string_callback($1->c_str()); %} %typemap(argout) const std::string & %{ //argout typemap for const std::string& %} %typemap(csin) std::string & "out $csinput" %typemap(throws, canthrow=1) string & %{ SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, $1.c_str()); return $null; %} } 

我需要为const std :: string&定义argout的原因是因为SWIG会混淆并覆盖const std :: string以及typemap。 所以我明确告诉它不要覆盖我的情况(你可能有不同的用例)

对于Python我创建了这样的东西:

 %typemap(argout)std::string& { //typemap argout std::string& PyObject* obj = PyUnicode_FromStringAndSize((*$1).c_str(),(*$1).length()); $result=SWIG_Python_AppendOutput($result, obj); } %typemap(argout) const std::string & %{ //argout typemap for const std::string& %}