Add method to class using Swig

I am in the process of packing a class in C ++ that needs to be subclassed in Python. To verify that this works correctly, I wanted to use the% extend swig option to add a test method to call from Python. Even using a very simple C ++ class that I dumped together, any attempt to add a method resulted in the following error:

Traceback (most recent call last):
  File "test.py", line 12, in <module>
    a.p()
  File "Monkey.py", line 87, in p
    def p(self): return _Monkey.Bar_p(self)
TypeError: in method 'Bar_p', argument 1 of type 'Bar *'`

How to add methods to a C ++ class using swig?

Example code used:

foo.h

class Bar
{
    public:
        Bar();
        virtual ~Bar();
        virtual void car() = 0;
};

Foo.i

%module(directors="1") Monkey
%{
#include <iostream>
#include "Foo.h"
%}

%include "Foo.h"

%feature("director") Bar::car;

%extend Bar
{
    void p()
    {
        std::cout<<"p";
    }
};
+3
source share

All Articles