Python SWIG: преобразовать указатель возвращаемого параметра C ++ в возвращаемое значение - PullRequest
0 голосов
/ 19 января 2020

Итак, ответ на этот вопрос точный. Однако, если вместо & мы используем *, что-то сломается, и я не знаю что. Ниже приведена измененная версия ...

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)

Дает мне эту ошибку ...

Exception ignored in: <built-in function delete_ResultType>
TypeError: delete_ResultType() takes no arguments (1 given)

И если я тогда попытаюсь сделать ...

print(r[0].x)

это выдаст похожую ошибку ...

TypeError: ResultType_x_get() takes no arguments (1 given)

Чтобы увидеть, что у меня есть python I сделал это ...

print(type(r[0]))

<class 'pyml.pyml.ResultType'>

print(dir(r[0]))

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__form
at__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_s
ubclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__',
 '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclas
shook__', '__swig_destroy__', '__weakref__', 'this', 'thisown', 'x', 'y']

Этот выглядит так, как я ожидал ... на самом деле, он выглядит точно так же, как когда вы используете & вместо *. .. так что похоже, что это должно работать. Но, увы, это не так.

Если я использую 0 вместо SWIG_POINTER_OWN в .i файле, TypeError: delete_ResultType() takes no arguments (1 given) исчезнет, ​​но я не уверен, что это правильно. Мне также удалось преобразовать два ResultTypes в пару кортежей в карте типов, но я бы предпочел иметь обернутый ResultType python.

В дополнение к ответу на этот конкретный c вопрос, кто-нибудь знает если есть лучшее место, чтобы задать вопросы Swig? Я чувствую, что публикация здесь не получает тяги.

Спасибо заранее!

...