【问题标题】:SWIG typemap from C char* to python string从 C char* 到 python 字符串的 SWIG 类型映射
【发布时间】:2016-11-26 10:55:28
【问题描述】:

我正在尝试使用 SWIG 在 Python 中使用 C 库。这个 C 库通过随处的参数传递函数结果。使用在线 SWIG 手册,我成功地将整数函数结果传递给 Python,但我很难弄清楚如何为字符串执行此操作。

这是我代码的精髓:

myfunc.c

#include <myfunc.h>

#include <stdio.h>


int mystr(int inp, char *outstr){
   outstr="aaa";
   printf("%s\n", outstr);
   return(0);
}

myfunc.h

extern int mystr(int inp, char *outstr);

所以基本上我的问题是 *outstr 的类型映射应该是什么样子。

提前致谢。

【问题讨论】:

  • 你真的是指outstr="aaa";吗?我怀疑你的意思是strcpy(outstr,"aaa");
  • 我猜我做到了。
  • 特别是outstr="aaa"; 不会改变调用者传入的字符串。outstr 参数在函数中被视为局部变量,所以outstr="aaa"; 只是使局部@987654328 @ 指向一个未命名的、已初始化的 4 个字符数组 { 'a', 'a', 'a'. '\0' }

标签: python c swig typemaps


【解决方案1】:

查看 SWIG 手册 9.3.4 String handling: cstring.i。这提供了几个用于char * 参数的类型映射。

可能(假设您确实在使用strcpy(outstr, "aaa"),如上面的评论中所述)您希望在您的 SWIG 接口文件中,在函数声明之前,例如:

%include <cstring.i>
%cstring_bounded_output(char* outstr, 1024);

【讨论】:

  • 感谢您的建议。我已经花了很多时间看手册,但由于我不是 C 编码员,我发现手册很难阅读,示例也不容易概括。
【解决方案2】:

通过修改SWIG 2.0 manual 的第 34.9.3 节中的示例,这就是我的工作方式:

%typemap(in, numinputs=0) char *outstr (char temp) {
   $1 = &temp;
}
%typemap(argout) char *outstr {

    PyObject *o, *o2, *o3;
    o = PyString_FromString($1);
    if ((!$result) || ($result == Py_None)) {
        $result = o;
    } else {
        if (!PyTuple_Check($result)) {
            PyObject *o2 = $result;
            $result = PyTuple_New(1);
            PyTuple_SetItem($result,0,o2);
        }
        o3 = PyTuple_New(1);
        PyTuple_SetItem(o3,0,o);
        o2 = $result;
        $result = PySequence_Concat(o2,o3);
        Py_DECREF(o2);
        Py_DECREF(o3);
    }
}

【讨论】:

  • 您的temp 只是一个char,因此如果您的outstr 超过1 个char,则此代码有时会出现段错误。否则,您的代码本质上是%cstring_bounded_output 的简化版本。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-09
  • 1970-01-01
  • 2015-09-02
  • 1970-01-01
  • 1970-01-01
  • 2021-06-22
  • 2022-01-06
相关资源
最近更新 更多