.NET StructureToPtr 和 PtrToStructure 求救

2540546520 2012-08-06 03:58:32
代码很简单,粘贴如下: 根据以下代码 给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);
}
}
}
...全文
146 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
2540546520 2012-08-10
  • 打赏
  • 举报
回复
嗯 改成char或byte array有改过 是可以 但是用string的话,有办法成功吗?
bdmh 2012-08-08
  • 打赏
  • 举报
回复
那你可以改用char[]或byte[]代替string
2540546520 2012-08-08
  • 打赏
  • 举报
回复
自己顶下
2540546520 2012-08-07
  • 打赏
  • 举报
回复
最后一个确实是被0给填充了 这个之前有测过 就是
struct SimpleStruct
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 5)]
public string AData;
public int AValue;
}
其中AData字段固定长度后就会少了一个字节,不固定长度可能是自动分配。
请问还有方法可以解决吗? 我这边是必须要固定一个长度的,除了比预设计的多分配一个unicode长度外还有其他方法吗?
bdmh 2012-08-06
  • 打赏
  • 举报
回复
只是怀疑, StructureToPtr 可能将字符串的最后一个字节当做结束符了,加上下面这句
byte[] blob = new byte[len];
Marshal.Copy(structPtr, blob, 0, len);
发现blob字段中有1,2,3,4 5的位置被0填充(结束符?)
有知晓的朋友可以告知一下

111,097

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧