c# - 如何在Python中将字节数组反序列化/序列化为结构体?

标签 c# python python-3.x

我有以下 C# 代码:

结构:

[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi, Size = 116)]
    public struct pLogin
    {
        public pHeader _header;

        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 12)]
        public string senha;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 12)]
        public string login;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
        public byte[] unk1;
        public int algo1;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 42)]
        public byte[] unk2;
        public short algo2;
        //versao do cliente
        public ushort cliver;
        public ushort unk3;
        public int umBool;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
        public byte[] mac;
    }
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi, Size = 12)]
    public struct pHeader
    {
        public ushort size;
        public byte key;
        public byte checksum;
        public ushort packetId;
        public ushort clientId;
        public uint timestamp;
    }

登录功能:

pLogin pLogin;
    public void iniciarLogin(string login, string senha, int cliver, string p_mac = "")
    {
        pLogin = new pLogin();
        pLogin._header = buildHeader(0x20D, 116);
        pLogin.senha = senha;
        pLogin.login = login;
        pLogin.cliver = (ushort)cliver;
        pLogin.umBool = 1;
        pLogin.algo1 = 132;
        pLogin.algo2 = 152;
        if (p_mac.Length == 0)
        {
            pLogin.mac = Encoding.ASCII.GetBytes(Functions.RandomString(16));
        }
        else
        {
            pLogin.mac = Functions.StringToByteArray(p_mac);
        }
        byte[] buffer = BufferConverter.StructureToBuffer<pLogin>(pLogin);
        EncDec.Encrypt(ref buffer);
        socket.Send(BufferConverter.StringToByteArray("11F3111F"));

        socket.Send(buffer);
        logger.Text += "[Cliente] Solicitando login...\n";

    }
pHeader packetHeader;
    private pHeader buildHeader(int _packetID, int size)
    {
        packetHeader = new pHeader();
        packetHeader.size = (ushort)size;
        packetHeader.key = EncDec.GetHashByte();
        packetHeader.checksum = 0;
        packetHeader.packetId = (ushort)_packetID;
        packetHeader.clientId = (ushort)serverData.playerMob.Mob.ClientId;
        packetHeader.timestamp = getCurrentTime();
        return packetHeader;
    }

现在是缓冲区转换器类:

public static Byte[] StructureToBuffer<T>(T structure)
    {
        Byte[] buffer = new Byte[Marshal.SizeOf(typeof(T))];

        unsafe
        {
            fixed (byte* pBuffer = buffer)
            {
                Marshal.StructureToPtr(structure, new IntPtr((void*)pBuffer), true);
            }
        }

        return buffer;
    }

    public static T BufferToStructure<T>(Byte[] buffer, Int32 offset)
    {
        unsafe
        {
            fixed (Byte* pBuffer = buffer)
            {
                return (T)Marshal.PtrToStructure(new IntPtr((void*)&pBuffer[offset]), typeof(T));
            }
        }
    }

上面的代码从结构中创建了一个带有登录数据的字节数组。 有没有办法在 python 中序列化/反序列化缓冲区数组? - 我不知道如何在 python 中做到这一点,因为我没有看到很多处理字节数组内容的文章。

最佳答案

当然有几种方法。

这是built-in struct module ,这需要一些手动工作来找出结构的格式字符串。

您还可以使用更高级别的第 3 方库,例如 construct (我可以推荐)。

使用 Construct,您的结构可能看起来像这样

Header = Struct(
    'size' / Int16ub,
    'key' / Int8ub,
    'checksum' / Int8ub,
    'packetId' / Int16ub,
    'clientId' / Int16ub,
    'timestamp' / Int32ub,
)
Login = Struct(
    "header" / Header,
    # ...
)

– C# 原始版本的相当简单的翻译,并且给定数据缓冲区,然后您可以执行类似

的操作
login_data = Login.parse(buffer)

关于c# - 如何在Python中将字节数组反序列化/序列化为结构体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56632419/

相关文章:

python - 如何在使用捕获组时修改字母数字字符的正则表达式

c# - 如何在 C# 中将此 SQL 转换为 LINQ?

c# - C++ Interop 的局限性(隐式 PInvoke)

python - 如何仅合并 Pandas 中的特定数据框列?

python - python(pycrypto) 和 nodejs(crypto) 之间的加密 (aes-128-cbc) 不匹配

python - 如何从两端迭代一个序列?

c# - 像这样优雅地重构代码(以避免出现标志)

c# - 对属性或调用方法使用空合并

python - 在 python 的类中使用函数(使用或不使用 self)

python - 如何获取 python 中具有最大值的列的列?