Segfault通过Boost Python在C ++对象之间传递共享指针 [英] Segfault from passing a shared pointer between C++ objects via Boost Python

查看:150
本文介绍了Segfault通过Boost Python在C ++对象之间传递共享指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个自定义的C ++类FooBaz,它们已经通过Boost Python成功地暴露给Python.用户与在后台运行其C ++对等物的Python类进行交互.一个重要的用例是将Foo Python实例传递给Python方法Baz.run_that_foo. Python的绑定方法是

I have two custom C++ classes Foo and Baz that I've successfully exposed to Python via Boost Python; the user interacts with Python classes that run their C++ counterparts under the hood. An important use case is passing a Foo Python instance to a Python method Baz.run_that_foo. The Python bindings method is,

// Note `XPython` is the name for the Boost Python bindings class of `X`.

void BazPython::RunThatFoo(const bp::object & foo) {
    FooPython & foo_obj = bp::extract<FooPython&>(foo);
    auto ps_ptr = foo_obj.GetPSPtr();
    Baz::DoPSComputation(ps_ptr);  // Expects a `const std::shared_ptr<planning_scene::PlanningScene>`
}

重要的是,ps_ptr应该是指向

Importantly, ps_ptr is supposed to be a shared pointer to a PlanningScene instance (i.e., std::shared_ptr<planning_scene::PlanningScene>), where that class is declared as,

class PlanningScene : private boost::noncopyable, public std::enable_shared_from_this<PlanningScene>

在我拥有的C ++ Foo类中,

In the C++ Foo class I have,

std::shared_ptr<planning_scene::PlanningScene> Foo::GetPSPtr() {  // two different attempts shown
    // return ps_;
    return (*ps_).shared_from_this();
}

其中,ps_是指向在Foo构造函数中通过std::make_shared创建的PlanningScene实例的有效共享指针.

where ps_ is a valid shared pointer to a PlanningScene instance created via std::make_shared in the Foo constructor.

运行一些C ++集成测试可以很好地工作,我直接在C ++中将foo_ptrFoo传递到Baz.但是python集成测试(使用bindings类)在Segmentation fault (core dumped)上失败.这有什么问题吗?我在Boost Python segfaults,enable_shared_from_this等上挖掘了许多SO问题,但无济于事.预先感谢!

Running some C++ integration tests works fine, where I pass a foo_ptr directly in C++ from Foo to Baz. But python integration tests (that use the bindings class) fail on Segmentation fault (core dumped). What could be wrong here? I've dug around many SO questions on Boost Python segfaults, enable_shared_from_this, etc., but to no avail. Thanks in advance!

推荐答案

诀窍是使用

The trick is to use boost::bind to generate a forwarding call wrapper around the method we're invoking from a Python-bindings class (i.e. FooPython.GetPSPtr):

void BazPython::RunThatFoo(const bp::object & foo) {
    FooPython & foo_obj = bp::extract<FooPython&>(foo);
    Baz::DoPSComputation(boost::bind(&Foo::GetPSPtr, &foo_obj)());
}

这篇关于Segfault通过Boost Python在C ++对象之间传递共享指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆