0

I am working on a research project calling some python functions from C and am trying to return a 256-byte bytearray from a python script to my C program using the python/C API. I am trying to store the returned byte array as a char array in my C program so I can later write it to a file, however when I try to convert the bytes PyObject using PyBytes_AsStringAndSize(), it only appears to write 8 bytes of data despite me specifying 256. Could anyone explain what is causing this behaviouir? I have tried scouring the documentation and online and haven't found help. Any ideas would be much appreciated!

int len = PyBytes_Size(pValue);  //pValue is the object returned from our python function
printf("C:object returned. Length of pValue Object: %i\n", len);

PyObject *pBytes = PyBytes_FromObject(pValue);   
int bLen = PyBytes_Size(pBytes);               
printf("C:object converted to bytes. Length of pBytes: %i\n", bLen);        
            
Py_ssize_t size = len;
char * test;

PyBytes_AsStringAndSize(pBytes,&test,&size); //Stores contents of returned pyobject into char array test
printf("Length of new byte array: %lu \n", sizeof(test));

I have looked all throughout the C/python api documentation and online but haven't found any clues so far.

Whenever the code is run, it produces the following output:

C:object returned. Length of pValue Object: 256

C:object converted to bytes. Length of pBytes: 256

Length of new byte array: 8 

BeeFriedman
  • 1,800
  • 1
  • 11
  • 29
  • 2
    `sizeof(test)` is only telling you "pointers are 64 bits", it doesn't tell you anything about the size of the thing pointed to. – hobbs Nov 17 '22 at 20:17
  • I see, i'm admittely pretty shaky on my C notation. What would the correct syntax to pass the contents of test? – Jordan RIchard Nov 17 '22 at 21:21
  • 1
    Nothing, sizeof doesn't do that. That's why `PyBytes_AsStringAndSize` outputs the size separately :) – hobbs Nov 17 '22 at 21:54
  • Bingo! I completely missed that size was an output variable of this function! Thanks a ton! – Jordan RIchard Nov 17 '22 at 22:22

0 Answers0