![](/img/trans.png)
[英]How to expose C++ virtual functions to python using boost/python?
[英]Extending C++ functions to Python using Boost Python
我正在尝试包装要在Python中使用的两个c ++文件。 我正在使用boost python库。 文件似乎可以正确编译,但是导入模块会导致“ ImportError:未定义符号”错误。
这个问题与boost没有正确找到依赖的c ++文件有关,但是我不清楚如何添加它们。
Python版本:2.7.12 Boost版本: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);
}
测试文件
#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正在查找hello.so
的版本,该版本是您在添加test.cpp
之前test.cpp
的。
我建议删除build
目录和hello.so
所有副本,然后再尝试从头开始运行构建。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.