[英]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. 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:使用 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' .但是当我尝试调用成员 function example_lib.lib.test(1)
时,我只得到类型 object 'lib' has no attribute 'test' 。 How do I make swig expose the member function as well?如何让 swig 也暴露成员 function? It seems like a very basic question but I would appreciate it very much if someone could clarify how it is usually done.这似乎是一个非常基本的问题,但如果有人能澄清它通常是如何完成的,我将非常感激。
Default accessibility is private
in C++, you then need to move it in a public:
section:默认可访问性在 C++ 中是private
的,然后您需要将其移动到public:
部分:
class lib{
public:
lib();
int test(int i);
};
Also note that test
is a instance method, you need to instantiate the class.另请注意, test
是一个实例方法,您需要实例化 class。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.