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

How to SWIG std::string& to C# ref string

本文关键字:string ref to SWIG 如何 std      更新时间:2023-10-16

我正在尝试将std::string引用的C 功能转换为C#。

我的API看起来像这样:

void GetStringDemo(std::string& str);

理想情况下,我想从c#

那里看到这样的东西
void GetStringDemoWrap(ref string);

我知道我需要为此创建一个Typemap,并且我尝试使用std_string.i文件尝试了一些事情,但是我认为我不会到达任何地方。有人有任何例子吗?我是Swig和C#的新手,所以我无法提出任何真正的想法。

以防万一有人在将来寻找这个,我为c#创建了std_string.i。似乎对我有用。请注意,我将裁判员更改为外面,因为在我的情况下这更合适,但裁判也应该工作。

我拨打了%files in .i file

/* -----------------------------------------------------------------------------
 * 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 <string>
%}
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&amp;的原因是因为Swig会感到困惑并覆盖const std :: string&amp;还有类型图。因此,我明确地告诉我不要在我的情况下覆盖(您可能有其他用例)

对于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&
%}
%typemap(in, canthrow=1) std::string & (std::string temp)
%{  
    //typemap in
    $1 = &temp; 
%}

在Alex的答案中,std::string temp应该位于顶部,以便SWIG如果您有多个OUT put。