.NET StructureToPtr 和 PtrToStructure 求救

2540546520 2540546520 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
代码很简单,粘贴如下: 根据以下代码 给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);
}
}
}
...全文

相关推荐

评论 5
收藏 已收藏
分享
返回顶部
2540546520
C# 111,129 成员 642,540 内容