Swig C++ to python:编译一堆.cpp和.h文件



我有一个C++库,由以下 cpp 和 h 文件组成。我希望将 cortex 中的函数.cpp公开给 Python (3.5)。

cortex.h
cortex_socket.h
cortex_intern.h
m3x3.h
cortex_unpack.h
m3x3.cpp
cortex_unpack.cpp  
cortex.cpp 
cortex_socket.cpp

我创建了以下 cortex.i 文件切换:

%module cortex
%{
#include "cortex.h"
#include "m3x3.h"
#include "cortex_intern.h"
#include "cortex_socket.h"
#include "cortex_unpack.h"
#include "stdbool.h"
%}
%include "cortex.h"

接下来,我使用以下命令来编译模块:

swig -python -Isrc cortex.i
g++ -Isrc -fPIC -I/usr/include/python3.5 -c cortex.cpp cortex_wrap.c
g++ -shared -fPIC -o _cortex.so cortex.o cortex_wrap.o

这些命令不会返回错误。但是,当尝试在 python 中使用生成的模块时,会弹出一个错误:

>>> import cortex
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "cortex.py", line 28, in <module>
    _cortex = swig_import_helper()
  File "cortex.py", line 24, in swig_import_helper
    _mod = imp.load_module('_cortex', fp, pathname, description)
ImportError: ./_cortex.so: undefined symbol: _Z13GetHostByAddrPhPc
>>> 

我在这个论坛上发现了与此错误有关的其他几个问题/答案。但是,由于我不熟悉swig anc C++我很难将这些转换为我自己的情况,代码和命令 - 换句话说:即使在阅读了这些其他帖子之后,我仍然迷失了方向。

我从网络上的各种来源收集了上面的代码片段。因此,如果有人向我解释这些代码行的作用(这可能有助于我找到解决方案),我将不胜感激。

无论如何,一些帮助会很棒。

包装C++代码时,使用"-c++"选项调用SWIG至关重要。

最新更新