I’m using embedded python in my C program. The python script grabs a file from an online source and returns the data it received.
The C part of my program that envolves this particular script is the following:
char* Drop::getFile(std::string path){
PyObject *pValue;
char* fileData = NULL;
pFunc = PyObject_GetAttrString(pModule,"getFile");
pArgs = PyTuple_New(1);
PyTuple_SetItem(pArgs,0,PyString_FromString(path.c_str()));
pValue = PyObject_CallObject(pFunc,pArgs);
fileData = PyString_AsString(pValue);
Py_DECREF(pFunc);
Py_DECREF(pArgs);
return fileData;
}
fileData does get a value, but the data it points to doesn’t match what the python script pulled from the net. What I’m testing this on is a pdf file
%PDF-1.4%âãÏÓ
194 0 obj<>endobj
xref
194 28
0000000016 00000 n
0000001374 00000 n
0000001521 00000 n
0000001915 00000 n
0000002047 00000 n
0000002547 00000 n
0000002661 00000 n
0000002773 00000 n
0000002800 00000 n
0000003401 00000 n
0000003656 00000 n
0000004166 00000 n
0000005703 00000 n
0000006124 00000 n
0000006373 00000 n
0000006828 00000 n
0000006898 00000 n
0000007022 00000 n
0000031268 00000 n
0000031531 00000 n
0000032131 00000 n
0000056344 00000 n
0000079808 00000 n
0000080674 00000 n
0000085029 00000 n
0000085946 00000 n
0000001196 00000 n
0000000873 00000 n
trailer
<> <6F4E88EE2CFAE8419CCB5AF471C4A73F>]/Prev 241987/XRefStm 1196>>
startxref
0
%%EOF221 0 obj<>stream
hÞb`bYÇÀÆÀÀÆ È
But the actual file is much longer. I’m at a lost on why the data is being cut.
You need to use
PyString_AsStringAndSizeand use the length of the file as well as the bytes returned. If you treat the returned bytes as a c-string, you’ll interpret the first 0-byte as the end of the string.In general, you must be careful when using string functions on binary data in C for exactly this reason.