![](/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.