简体   繁体   English

python嵌入后类型转换为结构

[英]Typecasting to a struct after python embedding

I have a small python script embedded in a C++ program. 我在C ++程序中嵌入了一个小的python脚本。 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. 将python对象暴露给C ++程序并将值复制到C ++变量后,我尝试将其类型转换为结构,但是我没有获得预期的值。 What is wrong here?] I am using python for socket programming to send data from one system to another. 这里出了什么问题?]我正在使用python进行套接字编程,以将数据从一个系统发送到另一个系统。

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. 提前致谢。

PyString_FromString assumes the passed string is terminated with a null byte like any normal C string. PyString_FromString假定传递的字符串以空字节结尾,就像任何普通的C字符串一样。 Your struct probably contains a null byte in it somewhere. 您的结构可能在某处包含一个空字节。 Use PyString_FromStringAndSize instead, which does not have that assumption. 请改用PyString_FromStringAndSize ,它没有该假设。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM