.NET StructureToPtr 和 PtrToStructure 求救
代码很简单,粘贴如下: 根据以下代码 给SimpleStruct结构体的AData字段输入12345 这5个字符,经过如下程序先把结构体转指针,再转回来,然后AData就突然变成1234了 少了个5 5呢? 5呢?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Collections;
namespace WindowsFormsApplication1
{
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 1)]
struct SimpleStruct
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 5)]
public string AData;
public int AValue;
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SimpleStruct data1 = new SimpleStruct();
data1.AValue = 1000;
data1.AData = textBox1.Text;
MessageBox.Show(Marshal.SizeOf(typeof(SimpleStruct)).ToString());
IntPtr structPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SimpleStruct)));
Marshal.StructureToPtr(data1, structPtr, true);
data1 = (SimpleStruct)Marshal.PtrToStructure(structPtr, typeof(SimpleStruct));
Marshal.FreeHGlobal(structPtr);
}
}
}