Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an object using Python's C API

Say I have my object layout defined as:

typedef struct {     PyObject_HEAD     // Other stuff... } pyfoo; 

...and my type definition:

static PyTypeObject pyfoo_T = {     PyObject_HEAD_INIT(NULL)     // ...      pyfoo_new, }; 

How do I create a new instance of pyfoo somewhere within my C extension?

like image 581
detly Avatar asked Nov 12 '10 09:11

detly


People also ask

What is C API in Python?

The Python/C API allows for compiled pieces of code to be called from Python programs or executed within the CPython interpreter. This process of producing compiled code for use by CPython is generally known as "extending" Python and the compiled pieces of code to be used are known as "extension modules".

What is C API?

CAPI (Common Application Programming Interface) is an international standard interface that application s can use to communicate directly with ISDN equipment. Using CAPI, an application program can be written to initiate and terminate phone calls in computers equipped for ISDN.

What is PyObject in Python?

PyObject is an object structure that you use to define object types for Python. All Python objects share a small number of fields that are defined using the PyObject structure. All other object types are extensions of this type. PyObject tells the Python interpreter to treat a pointer to an object as an object.


1 Answers

Call PyObject_New(), followed by PyObject_Init().

EDIT: The best way is to call the class object, just like in Python itself:

/* Pass two arguments, a string and an int. */ PyObject *argList = Py_BuildValue("si", "hello", 42);  /* Call the class object. */ PyObject *obj = PyObject_CallObject((PyObject *) &pyfoo_T, argList);  /* Release the argument list. */ Py_DECREF(argList); 
like image 181
Frédéric Hamidi Avatar answered Oct 05 '22 08:10

Frédéric Hamidi