[capi-sig] Passing an object from script to C code

Martin Poirier theeth at yahoo.com
Tue Jan 27 04:45:19 CET 2009


Hi,


--- On Mon, 1/26/09, Gamze Tunali <gdtunali at yahoo.com> wrote:

> From: Gamze Tunali <gdtunali at yahoo.com>
> Subject: [capi-sig] Passing an object from script to C code
> To: capi-sig at python.org
> Date: Monday, January 26, 2009, 9:56 PM
> 
> As a beginner, I have a question about passing a class
> instance from Python script to my C code. 
> What I am doing is basically creating a class in the
> script:
> 
> class dbvalue:
>   def __init__(self, index, type):
>     self.id = index    # unsigned integer
>     self.type = type   # string
> 
> last_roi = dbvalue(id, type);
> bmdl_batch.set_input_from_db(1, last_roi); <--------
> 
> I would like to call my C function with last_roi and able
> to recover id and type in the code. The C part is follows:
> 
> 
> PyObject *set_input_from_db(PyObject* self, PyObject *args)
> {
>   unsigned input;
>   PyObject *obj;
> 
>   if (!PyArg_ParseArg(args,
> "iO:set_input_from_db", &input, &obj))
>     return NULL;
> 
>   ....
> }
> 
> I am not sure if PyArg_ParseArg() is the right method to
> get the object.

It will work, but you should use PyArg_ParseTuple[1] instead, for the reasons explained in the api reference[2]. 

[1] http://docs.python.org/c-api/arg.html#PyArg_ParseTuple
[2] http://docs.python.org/c-api/arg.html#PyArg_Parse

> I used "O:.."  to get it but after
> that, how do I acces index and type fields of the object. Do
> I create an equivalent class/struct in C code to? Again, all
> I want is pass the 2 values together in an object and able
> to recover then in C code.

You can use PyObject_GetAttr (or PyObject_GetAttrString) from the Object protocol [3] to access attributes of an object.

Once you got your attribute, lets say your id field is a Python Integer which you want to convert to a C int, you can use the Integer object layer for that [4].

[3] http://docs.python.org/c-api/object.html
[4] http://docs.python.org/c-api/int.html

Hopefully, that pointed you in the right direction.

Martin


      


More information about the capi-sig mailing list