python 调用c 类_如何在Python中实现由C ++调用的C ++类?

最小的例子;请注意,由于Base不是纯虚拟的事实而使情况变得复杂。我们去了:

baz.cpp:

#include

#include

using std::string;

namespace py=boost::python;

struct Base{

virtual string foo() const { return "Base.foo"; }

// fooBase is non-virtual, calling it from anywhere (c++ or python)

// will go through c++ dispatch

string fooBase() const { return foo(); }

};

struct BaseWrapper: Base, py::wrapper{

string foo() const{

// if Base were abstract (non-instantiable in python), then

// there would be only this->get_override("foo")() here

//

// if called on a class which overrides foo in python

if(this->get_override("foo")) return this->get_override("foo")();

// no override in python; happens if Base(Wrapper) is instantiated directly

else return Base::foo();

}

};

BOOST_PYTHON_MODULE(baz){

py::class_("Base")

.def("foo",&Base::foo)

.def("fooBase",&Base::fooBase)

;

}

bar.py

import sys

sys.path.append('.')

import baz

class PyDerived(baz.Base):

def foo(self): return 'PyDerived.foo'

base=baz.Base()

der=PyDerived()

print base.foo(), base.fooBase()

print der.foo(), der.fooBase()

生成文件

default:

g++ -shared -fPIC -o baz.so baz.cpp -lboost_python `pkg-config python --cflags`

结果是:

Base.foo Base.foo

PyDerived.foo PyDerived.foo

在这里您可以看到fooBase()(非虚拟c ++函数)如何调用virtual foo(),无论使用c ++还是python,它都会解析为重写。您可以从c ++中的Base派生一个类,它的工作原理相同。

编辑(提取c ++对象):

PyObject* obj; // given

py::object pyObj(obj); // wrap as boost::python object (cheap)

py::extract ex(pyObj);

if(ex.check()){ // types are compatible

Base& b=ex(); // get the wrapped object

// ...

} else {

// error

}

// shorter, thrwos when conversion not possible

Base &b=py::extract(py::object(obj))();

py::object从构造PyObject*并用于py::extract查询python对象是否与您要提取的内容匹配:PyObject* obj; py::extract extractor(py::object(obj)); if(!extractor.check()) /* error */; Base& b=extractor();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值