SWIG: custom class objects as output argument (with Python)

(This is the question I asked yesterday, but I simplified it)

I created a class from which I want two objects to be the output arguments of a function (called Test below). But when I run the swig command swig -C ++ -python swigtest.i, I get the error message “Warning 453: Can not apply (MyClass & OUTPUT). I tried adding typemaps, but that doesn't help. I also tried using pointers pointers to pointers and links to pointers, which also does not help.

It seems to me that I missed something simple, because this should be a fairly common thing. Or do I need to write a complex map, as I saw, but don’t understand (yet)?

Below is my code:

MyClass.h (simplified to make it clear, so switching to just int doesn't help):

class MyClass
{
    int x;
public:
    int get() const
    {
        return x;
    }
};

void Test(MyClass &obj1, MyClass &obj2);

swigtest.i:

%module swigtest

%include typemaps.i

%{
#define SWIG_FILE_WITH_INIT
%}

%{
#include "MyClass.h"
%}

%include "MyClass.h"

%apply (MyClass& OUTPUT)  { MyClass &obj1 }
%apply (MyClass& OUTPUT)  { MyClass &obj2 }
+3
source share
3 answers

I decided to add additional Python code to swigtest.i, which completes the test function, so I can write obj1, obj2 = Test2(). I still think there should be a simpler solution,

//swigtest.i:

%module swigtest

%{
#define SWIG_FILE_WITH_INIT
#include "MyClass.h"
%}

%include "MyClass.h"

%insert("python") %{
    def Test2():
        obj1 = swigtest.MyClass()
        obj2 = swigtest.MyClass()
        swigtest.Test(obj1, obj2)
        return obj1, obj2
%}
0
source

As noted in my previous comment, the% apply OUTPUT trick only works for a limited set of POD types.

For future Swiggers, this solution worked for me (in C # bindings):

%typemap(cstype) CustomType* "out CustomType"
%typemap(csin,
   pre="    $csclassname temp$csinput = new $csclassname();",
  post="    $csinput = temp$csinput;"
) CustomType* "$csclassname.getCPtr(temp$csinput)"

"out" CustomType, . P/Invoke (csim) . "csin" .

, #, MyCustomType , , API, , "" ( , ).

+1

Try:

%module swigtest

%{
#define SWIG_FILE_WITH_INIT
#include "MyClass.h"
%}

%include "typemaps.i"
%apply MyClass *OUTPUT { MyClass &obj1, MyClass &obj2 };

%include "MyClass.h"

You can also create a wrapper that returns std :: list:

%include "std_list.i"
%ignore Test;
%rename(Test) TestWrap;
%inline %{
     std::list<MyClass> TestWrap() {
           MyClass obj1, obj2;
           Test(obj1, obj2);
           std::list<MyClass> tempList;
           tempList.push_back(obj1);
           tempList.push_back(obj2);
           return tempList;
     }
%}
0
source

All Articles