Boost::python和swig的集成

boost::python and swig integration

本文关键字:集成 swig python Boost      更新时间:2023-10-16

我有两个类,第一个叫做"Radish",第二个叫做"RadishCont"。所有代码都是用c++编写的,需要在python中使用。

萝卜已暴露于python使用SWIG;相反,RadishCont已经使用boost::python.

公开了。

我需要在RadishCont类中添加一个方法,它具有以下语法:

Radish* get_radish()
{
    return &radish;
}

其中"radish"是RadishCont中包含的一个萝卜实例。

当我执行python代码时,我收到这个异常:

TypeError: No Python class registered for C++ class Radish

所以,我的问题是:我怎么能使这个方法在python工作不重写RadishCont使用SWIG ?

我非常确定您最好重写SWIG接口以包含新函数。SWIG为类/函数使用了一个内部注册系统,这个系统与boost::python系统不兼容(或者至少不是开箱使用的)。

最后,我完成了。

我在boost python模块中创建了一个类实例,如下所示:

class_<Radish>("Radish");

我创建了一个像这样的转换器函数:

static void* radishConvert(PyObject* obj)
{
    char thisStr[] = "this";
    //first we need to get the this attribute from the Python Object
    if (!PyObject_HasAttrString(obj, thisStr))
            return NULL;
    PyObject* thisAttr = PyObject_GetAttrString(obj, thisStr);
    if (thisAttr == NULL)
            return NULL;
    //This Python Object is a SWIG Wrapper and contains our pointer
    void* pointer = ((PySwigObject*)thisAttr)->ptr;
    Py_DECREF(thisAttr);
    return pointer;
}

其中PySwigObject是一个像这样的结构体:

struct PySwigObject 
{
    PyObject_HEAD 
    void * ptr;
    const char * desc;
};

最后,我注册了转换器:

boost::python::converter::registry::insert(&radishConvert, type_id<Radish>());

这非常有效,我可以从SWIG获取对象并将其传递给boost::python。相反的过程仍然没有解决,但对我来说已经足够了。

这是我用来找到解决方案的指南:http://wiki.python.org/moin/boost.python/HowTo SWIG_exposed_C.2B -.2B -_object_from_Python

这个错误来自Boost.Python。BP的类型表中没有关于萝卜的条目。没有入口,BP就不知道该怎么做。获得参赛资格的唯一方法是用BP包裹萝卜。

恐怕BP和SWIG根本就不是一起工作的,而且我非常怀疑你会让他们按照你想要的方式工作,没有大规模的黑客攻击。

我建议您将整个系统移动到其中一个库,或者另一个