我在终端外壳上运行以下代码:
>>> import Strat
>>> x=Strat.Try()
>>> x.do_something()
You can do anything here!!!(this is the output of do_something)
但是在文件中调用同一文件时不起作用:
import Strat
class Strategy:
def gen_fibonacci(self,ind,n):
x=Strat.Try()
x.do_something()
l=[]
num = 3
t1 = 0
t2 = 1
nextTerm = 0
i=1
if ind==1:
l.append(0)
l.append(1)
i=3
if ind==2:
l.append(1)
i=2
while i<n:
nextTerm=t1+t2
t1=t2
t2=nextTerm
if num>=ind:
i=i+1
l.append(nextTerm)
num=num+1
return l
该代码给出以下错误:
Traceback (most recent call last):
File "./python_plugins/strat1.py", line 8, in gen_fibonacci
x=Strat.Try()
AttributeError: module 'Strat' has no attribute 'Try'
注意:此处Strat是具有类的共享库(so文件)尝试具有成员函数do_something()
strat.so文件是:的编译版本。
namespace python = boost::python; class Strat { public: virtual std::vector<long long> gen_fibonacci(int in,int n)= 0; }; struct Try { void do_something() { std::cout<<"You can do anything here!!!"<<"\n"; } }; class PyStrat final : public Strat , public bp::wrapper<Strat> { std::vector<long long> gen_fibonacci(int in,int n) override { get_override("gen_fibonacci")(); } }; BOOST_PYTHON_MODULE(Strat) { bp::class_<Try>("Try") .def("do_something", &Try::do_something) ; bp::class_<std::vector<long long> >("Long_vec") .def(bp::vector_indexing_suite<std::vector<long> >()) ; bp::class_<PyStrat, boost::noncopyable>("Strat") .def("gen_fibonacci", &Strat::gen_fibonacci) ; }
使用的编译命令:
g++ -I /usr/include/python3.6 -fpic -c -o Strat.o strat_helper.cpp g++ -o Strat.so -shared Strat.o -L/usr/lib/x86_64-linux-gnu -lboost_python3-py36 -lpython3.6m
我正在使用Boost python。
我在终端外壳上运行以下代码:>>> import Strat >>> x = Strat.Try()>>> x.do_something()您可以在这里做任何事情!!!(这是do_something的输出)...
我看到您正在尝试导入C ++函数。我希望您通过Framework on Using Boost并仔细阅读,可以帮助您解决问题,Extending Python with C or C++