Python SWIG: convert C++ return parameter to return value, and convert raw C++ type to Python type

后端 未结 1 1091
盖世英雄少女心
盖世英雄少女心 2021-01-03 16:56

I\'m trying to modify an existing SWIG Python interface for a C++ library, to add Python wrappers for more functions, and I would greatly appreciate some help from someone e

相关标签:
1条回答
  • 2021-01-03 17:53

    Just like $1 is a reference to the Python input object in the input typemap, $1 is a reference to the C++ output variable in the argout typemap. Using this, you can generate a Python object for that data and append it to the result.

    Here's a functional example for 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"
    

    Output

    >>> 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
    
    0 讨论(0)
提交回复
热议问题