我正在尝试打包两个要在 Python 中使用的 C++ 文件。我正在使用 boost python 库。文件似乎可以正确编译,但导入模块会导致“ImportError: undefined symbol ”错误。
这个问题与 boost 没有正确找到我依赖的 c++ 文件有关,但我不清楚如何添加它们。
Python 版本:2.7.12 升压版本:1.58 操作系统:Ubuntu 16.04
我的代码结构如下:
hellomodule.cpp
#include <iostream>
#include <cstdint>
#include "test.h"
using namespace std;
void say_hello(const char* name) {
cout << "Hello " << name << "!\n";
run_test();
}
#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
using namespace boost::python;
BOOST_PYTHON_MODULE(hello)
{
def("say_hello", say_hello);
}
测试.cpp
#include "test.h"
using namespace std;
void run_test(void){
cout << "Sup";
}
setup.py
#!/usr/bin/env python
from distutils.core import setup
from distutils.extension import Extension
module1 = Extension("hello",
sources = ["hellomodule.cpp", "test.cpp"],
libraries = ["boost_python"],
extra_compile_args=['-std=c++11'])
setup(name="PackageName",
ext_modules=[module1])
我从命令行运行“python setup.py build”来创建我的 hello.so 文件。当我尝试导入“hello”时,我得到“ImportError: ./hello.so: undefined symbol: _Z8run_testv”
如果有人能指出正确的方向,我将不胜感激。
最佳答案
您似乎有一些过时的文件。通过在 setup.py
中省略 sources
中的 test.cpp
,我能够重现该问题。在这种情况下,它构建得很好,但正如您所观察到的那样,它不会导入。可能是 Python 正在寻找您之前在添加 test.cpp
之前构建的 hello.so
版本。
我建议删除 build
目录和任何可能存在的 hello.so
拷贝,并尝试再次从头开始运行构建。
关于python - 使用 Boost Python 将 C++ 函数扩展到 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52104886/