rqly
rqly

Reputation: 13

How to call a C++ member function in python (SWIG)?

I want to expose my C++ library class to python and be able do call any function contained in that class in python. My example Library looks like this:

#include "example_lib.h"

lib::lib(){};
int lib::test(int i){
return i;
}

With the header:

class lib{
  lib();
  int test(int i);
};

My interface file:

/* example_lib.i */
%module example_lib
%{
   /* Put header files here or function declarations like below */
   #include "example_lib.h"
%}
%include "example_lib.h"

I run the following commands:

swig3.0 -c++ -python example_lib.i 
g++ -c -fPIC example_lib.cc example_lib_wrap.cxx -I/usr/include/python3.8
g++ -shared -fPIC example_lib.o example_lib_wrap.o -o _example_lib.so

but when I try calling the member function example_lib.lib.test(1), I only get type object 'lib' has no attribute 'test'. How do I make swig expose the member function as well? It seems like a very basic question but I would appreciate it very much if someone could clarify how it is usually done.

Upvotes: 0

Views: 204

Answers (1)

Jean-Baptiste Yunès
Jean-Baptiste Yunès

Reputation: 36441

Default accessibility is private in C++, you then need to move it in a public: section :

class lib{
  public:
    lib();
    int test(int i);
};

Also note that test is a instance method, you need to instantiate the class.

Upvotes: 3

Related Questions