通过插座在C 和Python之间进行固定的浮点阵列

Exchange fixed float array between C++ and python through socket

本文关键字:阵列 之间 插座 Python      更新时间:2023-10-16

我正在尝试使用c 发送固定长度的float数组并使用python

这是我的C 客户端,其中Sconnect是套接字对象

    float news[2];
    news[0] = 1.2;
    news[1] = 2.56;
    char const * p = reinterpret_cast<char const *>(news);
    std::string s(p, p + sizeof news);
    send(sConnect, &s[0], sizeof(news), 0);

和Python服务器我的代码就像

import socketserver

class MyTCPHandler(socketserver.BaseRequestHandler):
    def handle(self):
    self.data = self.request.recv(8).strip()
    print (self.data)
if __name__ == "__main__":
   HOST, PORT = "127.0.0.1", 9999
   print("listening")
   server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)
   server.serve_forever()

和我在Python获得的数据就像

b' x9a x99 x99? n xd7#@'

如何将其恢复回我发送的原始浮点数据?还是有更好的方式发送和接收数据?

您可以使用struct模块解开字节数据。

import struct
news = struct.unpack('ff', b'x9ax99x99?nxd7#@')
print(news)

使用您的代码:

import struct
import socketserver
class MyTCPHandler(socketserver.BaseRequestHandler):
    def handle(self):
        self.data = self.request.recv(8).strip()
        news = struct.unpack('ff', self.data)
        print(news)

struct.unpack,'ff'的第一个参数是指定数据预期布局的格式字符串,在这种情况下为2浮子。有关其他格式字符,请参见https://docs.python.org/3/library/struct.html。