Wednesday, February 13, 2013

Copying byte string from a C function to a Python string using ctypes


Disclaimer: I am no Python expert so if anyone has a better solution then let me know.

I was writing a script that would retrieve a byte string from a C library and copy it to a python string object.   I wanted to take those bytes and put them into a Python string object.
Per the ctypes documentation, setting the restype of the function to c_char_p would have simply returned a null-terminated string; a c_void_p is needed instead.

Sample C Function

extern "C" char* createBuffer(int* numBytes)
{
    char* myArray = new char[10000];
    //I'm just using memset to set the data.  
    //Of course your function will fill this array some other way
    memset(myArray, 0, 10000);       
    *numBytes = 10000;
    return myArray;
}

Python Code


from ctypes import *

libMyCLib = cdll.LoadLibrary('libMyCLib.so')
createBufferFunc = libMyCLib.createBuffer

createBufferFunc.restype = c_void_p
bufLen = c_int()

bufferPtr = createBufferFunc(byref(bufLen))

stringBuffer = create_string_buffer(bufLen.value)
memmove(stringBuffer, bufferPtr, bufLen.value)
bufferDataStr = stringBuffer[:]
#bufferDataStr is the python string object containing the buffer data