0

我正在用 boost::python 包装一个 C++ 框架,我需要在 python 中创建一个可覆盖的 C++ 方法。这是一个钩子方法,框架需要它并且在 C++ 中有一个默认实现,它遍历一个列表(作为参数传递)并执行一个选择。出现问题是因为选择是通过返回一个指向所选元素的指针(实际上是一个迭代器)来说明的,但是我找不到一种方法来返回一个 C++ 指针作为 python 函数的结果。任何人都可以帮忙吗?

谢谢

4

2 回答 2

0
// file: https://github.com/layzerar/box2d-py/blob/master/python/world.cpp
struct b2ContactFilter_W: b2ContactFilter, wrapper<b2ContactFilter>
{
    bool ShouldCollide(b2Fixture* fixtureA, b2Fixture* fixtureB)
    {
        override func = this->get_override("ShouldCollide");
        if (func)
        {
            return func(ref(fixtureA), ref(fixtureB)); //ref is boost::ref
        }
        return b2ContactFilter::ShouldCollide(fixtureA, fixtureB);
    }

    bool ShouldCollideDefault(b2Fixture* fixtureA, b2Fixture* fixtureB)
    {
        return b2ContactFilter::ShouldCollide(fixtureA, fixtureB);
    }
};

class_<b2ContactFilter_W, boost::noncopyable>("b2ContactFilter")
        .def("ShouldCollide", &b2ContactFilter::ShouldCollide, &b2ContactFilter_W::ShouldCollideDefault)
    ;

这是你需要的吗?

于 2012-12-21T06:03:19.087 回答
0

这当然是可行的,但你真的没有足够的细节。您真正需要做的是创建一个 c++ 函数来调用您的 python 函数,处理 python 结果并返回一个 c++ 结果。解释一下(假设我有一个object名为 func 的 boost,它指向一些解析字符串并返回 int 的 python 函数):

using boost::python;
A* test(const std::string &foo) {
    object module = import("mymodule");
    object func = module.attr("myfunc");
    // alternatively, you could set the function by passing it as an argument
    // to a c++ function that you have wrapped

    object result = func(foo);
    int val = extract<int>(result);
    return new A(val); // Assumes that you've wrapped A.
}
于 2012-12-17T05:05:18.943 回答