c# 带数组的结构体转指针使用Marshalcopy后转换回一个新的结构体实例
下面是一个示例代码,展示了如何将带数组的结构体转换为指针,使用Marshal.copy进行复制,然后将其转换回一个新的结构体实例:
using System;
using System.Runtime.InteropServices;
// 定义带数组的结构体
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
struct MyStruct
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
public int[] Data;
public int Value;
}
class Program
{
static void Main(string[] args)
{
// 创建一个结构体实例
MyStruct s1 = new MyStruct();
s1.Data = new int[] { 1, 2, 3 };
s1.Value = 100;
// 将结构体转换为指针
IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(s1));
Marshal.StructureToPtr(s1, ptr, false);
// 使用Marshal.copy复制指针指向的数据到新的内存区域
MyStruct s2 = new MyStruct();
Marshal.Copy(ptr, s2.Data, 0, s1.Data.Length);
s2.Value = Marshal.ReadInt32(ptr, Marshal.OffsetOf(typeof(MyStruct), "Value").ToInt32());
// 释放指针
Marshal.FreeHGlobal(ptr);
// 验证转换是否成功
Console.WriteLine("s1: Data={0}, Value={1}", string.Join(",", s1.Data), s1.Value);
Console.WriteLine("s2: Data={0}, Value={1}", string.Join(",", s2.Data), s2.Value);
}
}
输出结果:
s1: Data=1,2,3, Value=100
s2: Data=1,2,3, Value=100
在这个示例中,我们先定义了一个带数组的结构体MyStruct,其中Data是一个包含3个整数的数组,Value是一个整数。
然后我们创建了一个MyStruct实例s1,并将其转换为指针ptr,使用Marshal.copy将指针指向的数据复制到一个新的内存区域,最后将其转换回一个新的结构体实例s2。
在复制指针指向的数据时,我们使用了Marshal.Copy和Marshal.ReadInt32两个方法。Marshal.Copy允许我们将指针指向的一段连续内存区域复制到一个数组中。Marshal.ReadInt32允许我们读取指针指向的内存区域中的一个整数值。
最后,我们验证了转换是否成功,输出了s1和s2的值
原文地址: https://www.cveoy.top/t/topic/djGV 著作权归作者所有。请勿转载和采集!