public static IntPtr ToStructurePointer(this devinfo_t value) { var size = Marshal.SizeOf(value); var pointer = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(value, pointer, true); return(pointer); }
/// <summary> /// 打包 /// </summary> static (IntPtr ptr, int len) Pack() { var device = new DeviceInfo() { DEVINFO_TYPE_DID = "005", DEVINFO_TYPE_DEV_PRI_KEY = "dsajfdscSjdfaDDSKCNkdajcnAS11AS_", }; // 获取设备类型元数据 var type = typeof(DeviceInfo); var props = type.GetProperties(); // 设备结构体 var devInfo = new devinfo_t { filed = new string_t[props.Length], }; // 设置devinfo_t结构 for (int i = 0; i < props.Length; i++) { var s = (string)props[i].GetValue(device) ?? string.Empty; string_assign(out var st, s, s.Length); devInfo.filed[i] = st; } //for (int i = 0; i < devInfo.filed.Length; i++) //{ // var field = devInfo.filed[i]; // var s = Marshal.PtrToStringUTF8(field.s, field.len); //} // 打包为二进制数据 var ptr = devInfo.ToStructurePointer(); var pointer = HeyThings_devinfo_pack(ptr, 0, out var len); Console.WriteLine($"len: {len.ToString()}, ptr: {pointer.ToString()}"); var data = new byte[len]; Marshal.Copy(pointer, data, 0, len); Console.WriteLine($"Data: {BitConverter.ToString(data)}"); return(pointer, len); }