c# - 如何将 std::string& SWIG 转换为 C# 引用字符串

标签 c# c++ string swig

我正在尝试将带有 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 <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&
%}

关于c# - 如何将 std::string& SWIG 转换为 C# 引用字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13022051/

相关文章:

objective-c - 如何确定 NSString 中子字符串的顺序?

c# - 用 C# 编写的 WebJob 可以创建 Azure 数据库吗?

c# - 如何识别和存储文本框的更改详细信息并在 asp.net 中的 java 脚本中调用它

c++ - 将编译器生成的C++ lambda名称更改为易于阅读的名称

C++ 将字符串引用传递给函数

c - 如何计算在 C 中的可变参数函数中生成的字符串的长度?

Python 类型错误 : 'str' object is not callable when calling type function

c# - CancellationTokenSource.取消(假)

c# - 无法以编程方式设置 WPF 的 ComboBox 项文本

c++ - 修改 Makefile 以包含库并使用 C++11