Return a char array from Python extension module

1

I'm trying to build a simple C extension for Python, initially I'm trying to return the contents of an unsigned char array (binary data).

unsigned char frame_out[200];
// test data
for (int i = 0; i < 199; i++) {
    frame_out[i] = (i&0xff);
}
PyObject* result = Py_BuildValue("y#", frame_out, 199);
return result;

The code above works fine and I can print the test values in Python. But I want the array, frame_out, to be dynamic so I use new() as shown below.

char* frame_out = new char[200]
// test data
for (int i = 0; i < 199; i++) {
    frame_out[i] = (i&0xff);
}
PyObject* result = Py_BuildValue("y#", frame_out, 199);
return result;

This now gives an error when called from Python:

Process finished with exit code -1073741819 (0xC0000005)

I have also tried using malloc:

char* frame_out = (char* )malloc( sizeof(char) * 200);

But this gives the same error.

I have checked result and this is not null. What have I done wrong?

python
python-c-api
asked on Stack Overflow Aug 15, 2020 by Garry • edited Aug 15, 2020 by mkrieger1

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0