110,571
社区成员
发帖
与我相关
我的任务
分享
unsafe struct _s{
fixed int a[10];
};
_s s_obj;
Type t = typeof(_s);
foreach(FieldInfo f in t.GetFields()){
object o = f.GetVale(s_obj);
}
[DllImport("kernel32.dll", EntryPoint = "RtlMoveMemory", CharSet = CharSet.Ansi)]
public extern static long CopyMemory(IntPtr dest, IntPtr source, int size);
private void Form1_Load(object sender, EventArgs e)
{
_s s_obj=new _s();
//首先初始化s_obj中的数组a
int[] i = new int[] { 1, 2, 3,4,5,6,7,8,9,10 };
int k = Marshal.SizeOf(s_obj);
IntPtr ii = Marshal.AllocHGlobal(4 * 10);
Marshal.Copy(i, 0, ii, i.Length);
s_obj=(_s) Marshal.PtrToStructure(ii, typeof(_s));
Marshal.FreeHGlobal(ii);
Type t = typeof(_s);
FieldInfo[] fd = t.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
foreach (FieldInfo f in fd)
{
unsafe
{
//反射得到对象
object o =f.GetValue(s_obj);
//固定住对象,获取对象的地址
GCHandle gc = GCHandle.Alloc(o,GCHandleType.Pinned);
IntPtr addr = gc.AddrOfPinnedObject();
//确定该字段是否有FixedBufferAttribute属性
object[] attrs = f.GetCustomAttributes(typeof(FixedBufferAttribute), false);
if ((attrs != null) && (attrs.Length > 0))
{
FixedBufferAttribute attr = (FixedBufferAttribute)attrs[0];
Console.WriteLine("Tyep :{0} Name :{1}[{2}]", attr.ElementType.Name, f.Name, attr.Length);
Array ary = Array.CreateInstance(attr.ElementType, attr.Length);
IntPtr dest = Marshal.UnsafeAddrOfPinnedArrayElement(ary, 0);
int len = Marshal.SizeOf(attr.ElementType) * attr.Length;
//拷贝值到ary中
CopyMemory(dest, addr, len);
}
gc.Free();
}
}
}
unsafe struct _s
{
int c;
fixed int a[4];
fixed int b[5];
};
unsafe struct _SampleStruct
{
public fixed Int64 a[3];
public fixed Int32 b[5];
public int c;
}
unsafe struct _s
{
fixed int a[10];
fixed int b[20];
};
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Reflection;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
_s s_obj;
//首先初始化s_obj中的数组a
int[] i = new int[] { 1, 2, 3,4,5,6,7,8,9,10 };
int k = Marshal.SizeOf(s_obj);
IntPtr ii = Marshal.AllocHGlobal(4 * 10);
Marshal.Copy(i, 0, ii, i.Length);
s_obj=(_s) Marshal.PtrToStructure(ii, typeof(_s));
Marshal.FreeHGlobal(ii);
Type t = typeof(_s);
FieldInfo[] fd = t.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
foreach (FieldInfo f in fd)
{
unsafe
{
//反射得到对象
object o =f.GetValue(s_obj);
//固定住对象,获取对象的地址
GCHandle gc = GCHandle.Alloc(o,GCHandleType.Pinned);
IntPtr k1 = gc.AddrOfPinnedObject();
int[] i2 = new int[10];
//将值拷贝到数组i2中
Marshal.Copy(k1, i2, 0, i2.Length);
gc.Free();
}
}
}
unsafe struct _s
{
fixed int a[10];
};
}
}