您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

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

这是Windows的功能示例:

#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);

#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;
}

%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
python 2022/1/1 18:46:00 有315人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶