【问题标题】:How to SWIG std::string& to C# ref string如何 SWIG std::string& 到 C# 引用字符串
【发布时间】:2012-10-12 21:21:08
【问题描述】:

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

我的 API 如下所示:

void GetStringDemo(std::string& str);

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

void GetStringDemoWrap(ref string);

我知道我需要为此创建一个类型映射,并且我通过玩弄 std_string.i 文件尝试了一些事情,但我认为我没有得到任何结果。有没有人有任何例子。我对 Swig 和 C# 都是新手,所以我无法提出任何真正的想法。

【问题讨论】:

    标签: c# c++ string swig


    【解决方案1】:

    以防万一有人在未来寻找这个,我为 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 <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& 定义 argout 的原因是因为 SWIG 会混淆并使用类型映射覆盖 const std::string&。所以我明确告诉它不要在我的情况下覆盖(你可能有不同的用例)

    对于 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&
    %}
    

    【讨论】:

      【解决方案2】:
      %typemap(in, canthrow=1) std::string & (std::string temp)
      %{  
          //typemap in
          $1 = &temp; 
      %}
      

      在 Alex 的回答中,std::string temp 应该在最前面,这样如果你有多个输出,swig 会自动重命名变量。

      【讨论】:

        猜你喜欢
        • 2020-07-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-05
        • 1970-01-01
        • 2017-01-26
        相关资源
        最近更新 更多