如何在python(SWIG)中调用C++成员函数



我想向python公开我的C++库类,并能够在python中调用该类中包含的任何函数。我的示例库如下:

#include "example_lib.h"
lib::lib(){};
int lib::test(int i){
return i;
}

带标题:

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

我的接口文件:

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

我运行以下命令:

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

但是当我尝试调用成员函数时CCD_ 1,我只得到类型对象"lib"没有属性"test">。如何使swig也公开成员函数?这似乎是一个非常基本的问题,但如果有人能澄清通常是如何做到的,我将不胜感激。

默认的可访问性是C++中的private,然后您需要在public:部分中移动它:

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

还要注意,test是一个实例方法,您需要实例化该类。

最新更新