SWIG 结构指针作为输出参数

SWIG struct pointer as output parameter

我有一个结构:

struct some_struct_s {
   int arg1;
   int arg2;
};

我有一个 C 函数:

int func(some_struct_s *output);

两者都 %included 到我的 SWIG 文件中。

我希望 some_struct_s *output 被视为输出参数。 Python 示例:

int_val, some_struct_output = func()

"Output parameters" 包含在 POD 类型的手册中(第 10.1.3 节),但不包含非 POD 类型。

如何告诉 SWIG 我希望 some_struct_s *output 作为输出参数?

来自documentation

11.5.7 "argout" typemap

The "argout" typemap is used to return values from arguments. This is most commonly used to write wrappers for C/C++ functions that need to return multiple values. The "argout" typemap is almost always combined with an "in" typemap---possibly to ignore the input value....

这是您的代码的完整示例(为简洁起见没有错误检查):

%module test

// Declare an input typemap that suppresses requiring any input and
// declare a temporary stack variable to hold the return data.
%typemap(in,numinputs=0) some_struct_s* (some_struct_s tmp) %{
     = &tmp;
%}

// Declare an output argument typemap.  In this case, we'll use
// a tuple to hold the structure data (no error checking).
%typemap(argout) some_struct_s* (PyObject* o) %{
    o = PyTuple_New(2);
    PyTuple_SET_ITEM(o,0,PyLong_FromLong(->arg1));
    PyTuple_SET_ITEM(o,1,PyLong_FromLong(->arg2));
    $result = SWIG_Python_AppendOutput($result,o);
%}

// Instead of a header file, we'll just declare this code inline.
// This includes the code in the wrapper, as well as telling SWIG
// to create wrappers in the target language.
%inline %{

struct some_struct_s {
   int arg1;
   int arg2;
};

int func(some_struct_s *output)
{
    output->arg1 = 1;
    output->arg2 = 2;
    return 0;
}

%}

演示如下。请注意,int return 零值以及作为元组的输出参数被 return 编辑为列表。

>>> import test
>>> test.func()
[0, (1, 2)]

如果您不想要类型映射,您还可以注入代码来创建对象并return它对用户隐藏:

%module test

%rename(_func) func; // Give the wrapper a different name

%inline %{

struct some_struct_s {
   int arg1;
   int arg2;
};

int func(struct some_struct_s *output)
{
    output->arg1 = 1;
    output->arg2 = 2;
    return 0;
}

%}

// Declare your interface
%pythoncode %{
def func():
    s = some_struct_s()
    r = _func(s)
    return r,s
%}

演示:

>>> import test
>>> r,s=test.func()
>>> r
0
>>> s
<test.some_struct_s; proxy of <Swig Object of type 'some_struct_s *' at 0x000001511D70A880> >
>>> s.arg1
1
>>> s.arg2
2

如果您仔细 select SWIG 宏:

,您可以使类型映射语言不可知
%module test

%typemap(in,numinputs=0) struct some_struct_s *output %{
     = malloc(sizeof(struct some_struct_s));
%}

%typemap(argout) struct some_struct_s* output {
    %append_output(SWIG_NewPointerObj(,_descriptor,1));
}

%inline %{

struct some_struct_s {
   int arg1;
   int arg2;
};

int func(struct some_struct_s *output)
{
    output->arg1 = 1;
    output->arg2 = 2;
    return 0;
}

%}

演示:

>>> import test
>>> r,s=test.func()
>>> r
0
>>> s
<test.some_struct_s; proxy of <Swig Object of type 'some_struct_s *' at 0x000001DD0425A700> >
>>> s.arg1
1
>>> s.arg2
2