[英]Extending C++ functions to Python using Boost Python
I am trying to wrap up two c++ files to be used in Python. 我正在尝试包装要在Python中使用的两个c ++文件。 I am using the boost python library. 我正在使用boost python库。 The files appear to compile correctly, but importing the modules results in a "ImportError: undefined symbol" error. 文件似乎可以正确编译,但是导入模块会导致“ ImportError:未定义符号”错误。
This issue has something to do with boost not correctly finding my dependent c++ files, but I am not clear as to how to add them. 这个问题与boost没有正确找到依赖的c ++文件有关,但是我不清楚如何添加它们。
Python Version: 2.7.12 Boost Version: 1.58 OS: Ubuntu 16.04 Python版本:2.7.12 Boost版本:1.58操作系统:Ubuntu 16.04
My code structure is as follows: 我的代码结构如下:
hellomodule.cpp 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);
}
test.cpp 测试文件
#include "test.h"
using namespace std;
void run_test(void){
cout << "Sup";
}
setup.py 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])
From the command line I run "python setup.py build" which creates my hello.so file. 从命令行运行“ python setup.py build”,该文件创建了hello.so文件。 When I try to import "hello" I get "ImportError: ./hello.so: undefined symbol: _Z8run_testv" 当我尝试导入“ hello”时,出现“ ImportError:./hello.so:undefined symbol:_Z8run_testv”
If someone could please point me in the right direction, it would be greatly appreciated. 如果有人能指出我正确的方向,将不胜感激。
It seems like you may have some stale files around. 似乎您周围可能有一些过时的文件。 I was able to reproduce the issue by omitting test.cpp
from sources
in setup.py
. 我能够通过从setup.py
sources
中省略test.cpp
来重现该问题。 In this case it builds just fine, but as you observed, does not import. 在这种情况下,它可以很好地构建,但是正如您所观察到的那样,它不会导入。 It might be that Python is finding a version of hello.so
that you built previously before adding test.cpp
in. 可能是Python正在查找hello.so
的版本,该版本是您在添加test.cpp
之前test.cpp
的。
I'd suggest removing the build
dir and any copies of hello.so
that might be lying around and trying to run the build from scratch again. 我建议删除build
目录和hello.so
所有副本,然后再尝试从头开始运行构建。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.