从 pybind11 构建导入模块时出现"分段错误(核心转储)"



我在从 pybind11 构建导入模块时遇到了 python3 问题 在 Linux 中为 libpcap 导入的"pcap.h">

# test.cpp
#include "pybind11/pybind11.h"
#include "pybind11/stl.h"
#include "pcap.h"
void open_pcap(std::string &filename)
{
char errbuf[PCAP_ERRBUF_SIZE];
char *file_name = const_cast<char *>(filename.c_str());
// "segmentation fault" if i add bellow line
pcap_t *pcapfd = pcap_open_offline(file_name, errbuf);
}
namespace py = pybind11;
PYBIND11_MODULE(test, m)
{
m.def("open_pcap", &open_pcap);
}

编译成功

c++ -O3 -Wall -shared -std=c++11 -fPIC `python3 -m pybind11 --includes` test.cpp -o test`python3-config --extension-suffix`

但是当我从 python3 导入时,我遇到了错误

Python 3.6.9 (default, Nov  7 2019, 10:44:02) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
Segmentation fault (core dumped)

仅查看 python3 -v -c "导入测试"错误的信息

...
# /usr/lib/python3/dist-packages/apt/progress/__pycache__/text.cpython-36.pyc matches /usr/lib/python3/dist-packages/apt/progress/text.py
# code object from '/usr/lib/python3/dist-packages/apt/progress/__pycache__/text.cpython-36.pyc'
# /usr/lib/python3/dist-packages/apt/progress/__pycache__/base.cpython-36.pyc matches /usr/lib/python3/dist-packages/apt/progress/base.py
# code object from '/usr/lib/python3/dist-packages/apt/progress/__pycache__/base.cpython-36.pyc'
import 'fcntl' # <class '_frozen_importlib.BuiltinImporter'>
import 'apt.progress.base' # <_frozen_importlib_external.SourceFileLoader object at 0x7f583e1da7b8>
import 'apt.progress.text' # <_frozen_importlib_external.SourceFileLoader object at 0x7f583e20b2b0>
import 'apt.package' # <_frozen_importlib_external.SourceFileLoader object at 0x7f583fdad160>
# /usr/lib/python3/dist-packages/apt/__pycache__/cache.cpython-36.pyc matches /usr/lib/python3/dist-packages/apt/cache.py
# code object from '/usr/lib/python3/dist-packages/apt/__pycache__/cache.cpython-36.pyc'
import 'apt.cache' # <_frozen_importlib_external.SourceFileLoader object at 0x7f583fdbd2b0>
# /usr/lib/python3/dist-packages/apt/__pycache__/cdrom.cpython-36.pyc matches /usr/lib/python3/dist-packages/apt/cdrom.py
# code object from '/usr/lib/python3/dist-packages/apt/__pycache__/cdrom.cpython-36.pyc'
import 'apt.cdrom' # <_frozen_importlib_external.SourceFileLoader object at 0x7f583e1f30b8>
Segmentation fault (core dumped)

通过在构建模块时向命令行添加-lpcap来与 libpcap 链接。

对我来说,问题在于我正在构建的Python版本。我在python3.8的虚拟环境中,但我使用的是默认的编译命令,默认为python3.6

损坏的命令:

c++ -O3 -Wall -shared -std=c++11 -fPIC `python3 -m pybind11 --includes` python-binding.cpp  -o matchNotification`python3-config --extension-suffix`

工作命令:

c++ -O3 -Wall -shared -std=c++11 -fPIC `python3 -m pybind11 --includes` python-binding.cpp  -o matchNotification`python3.8-config --extension-suffix`

滚动到命令的末尾以查看更改

最新更新