python - 使用 Boost Python 将 C++ 函数扩展到 Python

标签 python c++ boost-python

我正在尝试打包两个要在 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/

相关文章:

python - 检索满足某些条件的字典

c++ - 使用 boost 几何旋转多边形

python - 如何使用 boost.python 将预填充的 "unsigned char*"缓冲区传递给 C++ 方法?

c++ - 使用 Boost.Python 公开带有 unsigned char 和参数的方法

python - OpenCV python3无法正确旋转图像

python - 将 GAE 远程 API 连接到 dev_appserver.py

Python请求不会通过get方法中的参数添加查询字符串

c++ - 保护 COM 接口(interface)免受异常影响

c++ - 从函数 C++ 返回数组

python - Python 3 无法通过 Boost.Python 嵌入将 C++ 类识别为模块