Passing binary data from Python to the C API extension

I am writing a Python extension ( 2.6 ) and I have a situation where I need to pass an opaque binary blob (with embedded null bytes) to my extension.

Here is a snippet of my code:

from authbind import authenticate creds = 'foo\x00bar\x00' authenticate(creds) 

which produces the following:

 TypeError: argument 1 must be string without null bytes, not str 

Here are some of authbind.cc:

 static PyObject* authenticate(PyObject *self, PyObject *args) { const char* creds; if (!PyArg_ParseTuple(args, "s", &creds)) return NULL; } 

So far, I tried passing blob as a raw string, for example creds = '%r' % creds , but this not only gives me inline quotes around the string, but also turns the \x00 bytes into their literal string representations, which I do not want to get around using C.

How can I accomplish what I need? I know about format characters y , y# and y* PyArg_ParseTuple () in 3.2, but I'm limited to 2.6.

+4
source share
1 answer

Ok, I found out using this link .

I used PyByteArrayObject (docs here ) as follows:

 from authbind import authenticate creds = 'foo\x00bar\x00' authenticate(bytearray(creds)) 

And then into the extension code:

 static PyObject* authenticate(PyObject *self, PyObject *args) { PyByteArrayObject *creds; if (!PyArg_ParseTuple(args, "O", &creds)) return NULL; char* credsCopy; credsCopy = PyByteArray_AsString((PyObject*) creds); } 

credsCopy now contains a string of bytes exactly as they are needed.

+3
source

All Articles