.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);
}
}
}
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);
}
}
}
...全文
相关推荐
自己实现的一个资源化窗体方案-当前所有打开的窗体得以应用
http://topic.csdn.net/u/20100918/22/aa97ad9a-5e56-40d2-9057-04ceeb717855.html?seed=1673304571&r=68525251#r_68525251 这个帖子的问题答案,顺道贴来,希望日后有人用的到可以省了力气。 这是刚才范例的升级版本。支持对当前的所有窗体应用。
C#结构体和C++字节数组的转换
在写C#TCP通信程序时,发送数据时,只能发送byte数组,处理起来比较麻烦不说,如果是和VC6.0等写的程序通信的话,很多的都是传送结构体,在VC6.0中可以很方便的把一个char[]数组转换为一个结构体,而在C#却不能直接把byte数组转换为结构体,要在C#中发送结构体,可以按此方法实现。
Marshal类的使用
Marshal类的简单使用,博客:http://blog.csdn.net/dingxiaowei2013/article/details/23934693
官方VB.net WM_COPYDATA进行进程间资源共享的例子
官方VB.net 通过WM_COPYDATA消息机制,进行进程间资源共享的例子
C#—EMguCV Marshal
将数据从托管对象封送到非托管内存块,属于.NET Framework 类库


