Как выставить пользовательские типы данных с помощью Boost.Python - PullRequest
0 голосов
/ 11 апреля 2019

Мне интересно, как предоставить пользовательские типы данных с помощью 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,   
};

Как я могу предоставить этот custom_number тип данных, используя C ++ Boost.Python, чтобы иметь возможность создать экземпляры custom_number в коде python?

Я пытался

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&)’

Есть предложения?

Спасибо!

...