从 pybind11 构建导入模块时出错 "Segmentation fault (core dumped)"

Error "Segmentation fault (core dumped)" when import module built from pybind11

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

中为 libpcap 导入
# 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 "import test"

查看错误信息
...
# /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)

Link 通过在构建模块时将 -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`

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