示例.h:
#ifndef EXAMPLE_H
#define EXAMPLE_H
class Math {
public:
int pi() const;
void pi(int pi);
private:
int _pi;
};
#endif
示例.cpp:
#include "example.h"
int Math::pi() const {
return this->_pi;
}
void Math::pi(int pi) {
this->_pi = pi;
}
示例.swig:
%module example
%{
#define SWIG_FILE_WITH_INIT
#include "example.h"
%}
%include "example.h"
然后我使用以下方法生成包装器“example.py”和“example_wrap.c”:
swig -python example.swig
当我尝试使用以下方法编译包装类时:
g++ -fPIC -c example.cpp example_wrap.c -I/usr/local/include/python2.6/
我收到以下错误:
example_wrap.cpp: In function "PyObject* Swig_var_Math_get()":
example_wrap.cpp:2725: error: expected primary-expression before "void"
example_wrap.cpp:2725: error: expected ")" before "void"
错误位于以下行:
pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(&Math), SWIGTYPE_p_class, 0 );
#define SWIG_as_voidptr(a) (void *)((const void *)(a))
生成包装类“example_wrap.c”的正确方法是吗?
我认为 swig 命令应该是“swig -c++ -python example.swig”
这里没有足够的信息来确定出了什么问题,但我有两个想法你可以尝试。
您的
g++
调用正在编译 C 源文件,就好像它是 C++ 一样。这不保证有效。试试吧
gcc -I/usr/local/include/python2.6 -fPIC -c example_wrap.c
gcc -I/usr/local/include/python2.6 -fPIC -c example.cpp
g++ -shared example_wrap.o example.o -o example.so
(是的,srsly,仅使用 g++ 作为链接)
如果这不起作用,请像这样编译
example_wrap.c
:
gcc -I/usr/local/include/python2.6 -fPIC -c -save-temps example_wrap.c
这也会以同样的方式失败,但会生成一个名为
example_wrap.i
的文件,这是预处理的结果。它将是巨大的。在该文件中搜索函数 Swig_var_Math_get
,并将该函数的 完整文本 添加到您的问题中(仅此而已)。
谢谢您的回复!
-c++
选项更好地为包装器生成实际的C++类(-v
代表verbose模式):
swig -c++ -v -python example.swig
然后我使用 g++ 编译包装器:
g++ -fPIC -c example.cpp example_wrap.cxx -I/usr/local/include/python2.6/
以及以下命令来构建共享对象。当然,您可能需要删除多余的包含(
-I
)和库(-L
)。重要的标志是 -shared
和 -fPIC
。
g++ example_wrap.o example.o -L/u01/app/oracle/product/1020.full/lib -I/usr/local/ssl/include -L/usr/local/ssl/lib -lclntsh -lssl -lcrypto -ldl -L/usr/local/lib -L/lib64 -L/usr/local/lib/python2.6/ -lboost_system -lboost_filesystem -lboost_thread -lboost_date_time -lglog -lmodpbase64 -lpthread -ldl -lrt -shared -fPIC -o _example.so