如何使用Boost.Python

时间:2019-04-11 08:03:37

标签: c++ python-3.x boost-python

我想知道如何使用Boost.Python公开自定义数据类型。

例如,假设我有一个名为 custom_number 的自定义数据类型:

typedef struct 
{
    PyObject_HEAD
    int x;
} custom_number;

static int custom_number_init(PyObject *self, PyObject *args, PyObject *kwds)
{
    static char* nams[] = {"x", NULL};
    int x;
    if(!PyArg_ParseTupleAndKeywords(args, kwds, "i", nams, &x))
        return -1;

    ((vector*)self)->x = x;

    return 0;
}

static PyObject *custom_number_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
    vector *self;
    self = (vector *) type->tp_alloc(type, 0);
    if (self != NULL) 
    {
        self->x = 0;
    }

    return (PyObject *) self;
}

static void custom_number_dealloc(PyObject *self)
{
    self->ob_type->tp_free(self);
}

static PyMemberDef custom_number_members[] = {
    {"x", T_INT, offsetof(vector, x), 0, "silly number!" },
    {NULL}
};

static PyTypeObject custom_number_Type = {
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "vector",
    .tp_basicsize = sizeof(custom_number),
    .tp_itemsize = 0,
    .tp_dealloc = (destructor) custom_number_dealloc,
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,       
    .tp_doc = "custom_number type",  
    .tp_members = custom_number_members,     
    .tp_init = (initproc) custom_number_init,
    .tp_new = custom_number_new,   
};

如何使用C ++ Boost.Python公开此 custom_number 数据类型,以便能够 在python代码中创建 custom_number 的实例?

我尝试过

BOOST_PYTHON_MODULE(test)
{
  namespace python = boost::python;

  python::class_<custom_number>("custom_number",boost::python::init<int>());

}

但得到:

error: no matching function for call to ‘custom_number::custom_number(const int&)’

有什么建议吗?

谢谢!

0 个答案:

没有答案