0

I have a small python script embedded in a C++ program. After exposing the python object to C++ program and copying the value to a C++ variable, i try to typecast it to a struct, but i do not get the expected value. What is wrong here?] I am using python for socket programming to send data from one system to another.

The code looks like this.

#include
#include


struct overhead{

    uchar8 flags;
    uint16 seqNo, timeDiff, threshold, length;  

};

struct payload{

    float forceX,forceY,forceZ,positionX,positionY,positionZ;

};

struct packet{

    overhead fields;
    payload data;

};

const char * msg;

int main(){

    packet pack;

    /* assign values to members of packet
    pack.fields.threshold = 
    pack.data.forceZ = */

    msg = (const char *) &pack;

    PyObject *PyMain = PyImport_AddModule("__main__");
    PyObject *globals = PyModule_GetDict(PyMain);

    PyObject *string = PyString_FromString(msg);
    PyDict_SetItemString(globals, "send", string);

    const char* sendPy = "UDPSock.sendto(send,('10.107.35.167',2000))";
    PyRun_SimpleString(sendPy);

    PyObject *temp = PyDict_GetItemString(globals, "send");
    const char* x = PyString_AsString(temp);

    packet *pa = (packet *) x;
    cout << pa->data.forceZ << endl; 



}

But the output is not the same as the value assigned. Can anybody explain what is wrong?

Thanks in advance.

Vigo
  • 707
  • 4
  • 11
  • 29

1 Answers1

0

PyString_FromString assumes the passed string is terminated with a null byte like any normal C string. Your struct probably contains a null byte in it somewhere. Use PyString_FromStringAndSize instead, which does not have that assumption.

icktoofay
  • 126,289
  • 21
  • 250
  • 231