Python SWIG:将C ++返回参数转换为返回值,并将原始C ++类型转换为Python类型

问题描述 投票:1回答:1

我正在尝试为C ++库修改现有的SWIG Python接口,为更多功能添加Python包装器,我非常感谢SWIG经验丰富的人提供的一些帮助。

具体来说,我正在使用这样的签名函数:

void execute(int x, double y, ResultType& result1, ResultType& result2);

此函数接受两个空的ResultType对象,并将它们作为输出参数填充。在Python中,这必须转换为只接受xy的函数,然后返回result1result2的元组。

ResultType是一种在整个库中广泛使用的容器类型。

类型表(中)

从研究中,我想我明白我需要为result1和result2添加一个“in”类型,它会吞下参数并将它们保存到临时变量中。我还发现引用被SWIG转换为指针,因此&temp而不是temp。这是我的typemap“in”:

typemap(in, numinputs=0) ResultType& result1 (ResultType temp) {
    $1 = &temp;
}

typemap(in, numinputs=0) ResultType& result2 (ResultType temp) {
    $1 = &temp;
}

类型表(argout)

接下来,我添加了一个类型映射“argout”,它将值附加到返回元组:

%typemap(argout) ResultType& result1 {
    $result = SWIG_Python_AppendOutput($result, temp$argnum);
}

%typemap(argout) ResultType& result2 {
    $result = SWIG_Python_AppendOutput($result, temp$argnum);
}

然而,这显然是行不通的,因为temp$argnum将是原始的C ++类型ResultType,而我需要有一个PyObject *才能附加到元组。 ResultType已经有一个工作的SWIG包装器。所以,在Python中我可以调用ResultType()来构造它的实例而没有问题。假设到目前为止我在正确的轨道上,如何将原始C ++ ResultType对象转换为属于SWIG生成的PyObject *包装器的ResultType? (对不起,如果细节太多,我试图避免“XY问题”)

python c++ swig
1个回答
2
投票

就像$ 1是对输入类型映射中的Python输入对象的引用一样,$ 1是对argout typemap中的C ++输出变量的引用。使用此方法,您可以为该数据生成Python对象并将其附加到结果中。

这是Windows的功能示例:

test.h

#ifdef EXPORT
#define API __declspec(dllexport)
#else
#define API __declspec(dllimport)
#endif

struct ResultType
{
    int x;
    double y;
};

API void execute(int x, double y, ResultType& result1, ResultType& result2);

TEST.CPP

#define EXPORT
#include "test.h"

API void execute(int x, double y, ResultType& result1, ResultType& result2)
{
    result1.x = 2 * x;
    result1.y = 2 * y;
    result2.x = 3 * x;
    result2.y = 3 * y;
}

test.i

%module test

%{
#include "test.h"
%}

%include <windows.i>

%typemap(in,numinputs=0) ResultType& %{
    // Create a persistent object to hold the result;
    $1 = new ResultType;
%}

%typemap(argout) ResultType& (PyObject* tmp) %{
    // Store the persistent object in a PyObject* that will be destroyed
    // when it goes out of scope.
    tmp = SWIG_NewPointerObj($1, $1_descriptor, SWIG_POINTER_OWN);
    $result = SWIG_Python_AppendOutput($result, tmp);
%}

%include "test.h"

产量

>>> import test
>>> r = test.execute(2,3)
>>> r[0].x
4
>>> r[0].y
6.0
>>> r[1].x
6
>>> r[1].y
9.0
© www.soinside.com 2019 - 2024. All rights reserved.