110,536
社区成员
发帖
与我相关
我的任务
分享
[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ansi, Size = 28)]
struct StudentInfo
{
// 看这里,UnmanagedType.ByValTStr 和 CharSet = CharSet.Ansi决定了你取到的字符串具体是由什么类型来的。
// 你需要做的就是,把这个值和实际的数据匹配上,不明白就每种都试一下。
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 24), FieldOffset(0)]
public string str;
[FieldOffset(24)]
public int intId;
}
List<StudentInfo> st = MarshalPtrToStructArray<StudentInfo>(pStudentInfo, intCount);
// 这个intCount,是你统共从这个指针里面取出多少条数据,不是当前数据的编号。。。
MessageBox.Show(st[9].str);
这个是最后一条数据。。。
list都有了,还不会取数据么。。。
private void Form1_Load(object sender, EventArgs e)
{
}
[DllImport("ddd.dll")]
extern static int GetStudentInfo(IntPtr pStudentInfo);
[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ansi, Size = 28)]
struct StudentInfo
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 24), FieldOffset(0)]
public string str;
[FieldOffset(24)]
public int intId;
}
public static List<T> MarshalPtrToStructArray<T>(IntPtr p, int count)
{
List<T> l = new List<T>();
for (int i = 0; i < count; i++, p = new IntPtr(p.ToInt32() + Marshal.SizeOf(typeof(T))))
{
T t = (T)Marshal.PtrToStructure(p, typeof(T));
l.Add(t);
}
return l;
}
private void button1_Click(object sender, EventArgs e)
{
IntPtr pStudentInfo = Marshal.AllocHGlobal(280);
int intCount = GetStudentInfo(pStudentInfo);
List<StudentInfo> st = MarshalPtrToStructArray<StudentInfo>(pStudentInfo, intCount);
MessageBox.Show(st[9].str);
}