Adam Lewis
Adam Lewis

Reputation: 7257

How do I cast a Python object to a C variable?

Pretty straight forward I would think. I'm very confident it's one of the cases where I don't know how to ask the simple question.

Trying to cast a python object (list) to an array of unsigned chars.

PyObject * py_data;
unsigned char c_data[MAX_LENGTH];

// py_data is filled using the PyArg_ParseTuple(....)

// Build the outbound payload
for(i=0; i < block_length; i++)
{
    c_data[i] = HOW_TO_CAST_THIS(py_data[i]);
}

I have read the tutorial written by Ned Batchelder which is a great read, as well as Googled with no luck.

Any other tutorials or reference recommendations would be great.

Upvotes: 0

Views: 689

Answers (1)

nneonneo
nneonneo

Reputation: 179422

To get items out of a tuple, you have to use PyTuple_GetItem (or, if you know it's a tuple, you can use the unsafe PyTuple_GET_ITEM). This gives you PyObjects.

To get ints from the PyObjects, use PyInt_AsLong.

NEVER cast PyObjects to C types (other than void *), and never attempt to index a PyObject using indexing notation (py_data[i]). Both will give you very bad results. Always use Python API methods to deal with PyObjects.

Upvotes: 3

Related Questions