Categories

See More
Popular Forum

MBA (4887) B.Tech (1769) Engineering (1486) Class 12 (1030) Study Abroad (1004) Computer Science and Engineering (988) Business Management Studies (865) BBA (846) Diploma (746) CAT (651) B.Com (648) B.Sc (643) JEE Mains (618) Mechanical Engineering (574) Exam (525) India (462) Career (452) All Time Q&A (439) Mass Communication (427) BCA (417) Science (384) Computers & IT (Non-Engg) (383) Medicine & Health Sciences (381) Hotel Management (373) Civil Engineering (353) MCA (349) Tuteehub Top Questions (348) Distance (340) Colleges in India (334)
See More
( 8 months ago )

How to expose custom data types using Boost.Python

General Tech Bugs & Fixes
Max. 2000 characters
Replies

usr_profile.png
Ekta Singhania

User

( 8 months ago )

 

I am wondering how to expose custom data types using Boost.Python.

For example, say I have a custom datatype called 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)
			
        

what's your interest