python - 序列化 ctype 联合

标签 python networking serialization union ctypes

有没有办法序列化 ctype 联合以便通过套接字发送它们?我试图通过套接字将联合发送到网络服务器,但我无法序列化数据,而是作为联合对象的实例发送。是否可以使用 Python Struct() 库来执行此操作(我不相信它支持联合)?非常感谢任何帮助!

最佳答案

如果您在 ctypes.Structurectypes.Union 上调用 bytes(),您将获得底层字节字符串,可以是通过套接字传输。收到后,将该字节字符串复制回原始对象。

这是一个独立的例子。套接字服务器作为线程启动,并将向客户端发送两个对象。客户端然后接收对象并解释它:

import ctypes
import socket
import threading

# Used to indicate what type of field is in the Union.
U32 = 1
DBL = 2

class MyUnion(ctypes.Union):
    _fields_ = ('u32',ctypes.c_uint32),('dbl',ctypes.c_double)

class MyStruct(ctypes.Structure):
    _pack_ = 1  # define before _fields_ to have an affect.
    _fields_ = ('type',ctypes.c_int),('u',MyUnion)

def client():
    s = socket.socket()
    s.connect(('localhost',5000))

    # Wrap the socket in a file-like object so an exact amount of bytes can be read.
    r = s.makefile('rb')

    # Read two structures from the socket.
    ex1 = MyStruct.from_buffer_copy(r.read(ctypes.sizeof(MyStruct)))
    ex2 = MyStruct.from_buffer_copy(r.read(ctypes.sizeof(MyStruct)))
    s.close()

    # display the correct Union field by type.
    for ex in (ex1,ex2):
        if ex.type == U32:
            print(ex.u.u32)
        else:
            print(ex.u.dbl)

def server():
    s = socket.socket()
    s.bind(('',5000))
    s.listen(1)
    c,a = s.accept()

    # Prepare two structures
    ex1 = MyStruct()
    ex1.type = DBL
    ex1.u.dbl = 1.234
    ex2 = MyStruct()
    ex2.type = U32
    ex2.u.u32 = 1234

    # Send them as bytes
    c.sendall(bytes(ex1))
    c.sendall(bytes(ex2))

    c.close()
    s.close()

# spin off the server in a thread so the client can connect to it.
t = threading.Thread(target=server)
t.start()

client()

输出:

1.234
1234

关于python - 序列化 ctype 联合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56927991/

相关文章:

c# - 在 C# 中切换类类型

Python Marshmallow 和 PyCharm 类型提示

python - 使用 Python 循环使用随机范围的列表

Python如何从字符串中提取括号包围的数据

c++ - 从套接字转换(解析)谷歌 Protocol Buffer 流

android - "netcfg wlan0 up"应用程序不工作

python - 根据列表的长度传递给 python 方法

python - 计算其他列上给定条件的列类别的唯一值

c - 使用 ZeroMQ 发现服务

c++ - 最佳实践 : how to interpret/process QDataStream?