C# 怎么将ushort数组里面的数据拷贝到IntPtr里面去啊
展开全部
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
ushort[] uData = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };//ushort数组
IntPtr ptr = Marshal.AllocHGlobal(uData.Length * Marshal.SizeOf(typeof(ushort)));//分配内存
List<byte> bytes = new List<byte>();
foreach (ushort u in uData)
{
bytes.AddRange(BitConverter.GetBytes(u));
}
Marshal.Copy(bytes.ToArray(), 0, ptr, bytes.Count);//拷贝
//读取测试
byte[] data = new byte[bytes.Count];
Marshal.Copy(ptr, data, 0, data.Length);//读出来
ushort[] readData = new ushort[uData.Length];
for (int i = 0; i < readData.Length; i++)
{
//还原数组
readData[i] = BitConverter.ToUInt16(data, i * Marshal.SizeOf(typeof(ushort)));
Console.Write(readData[i] + " ");
}
Marshal.FreeHGlobal(ptr);//用完以后释放内存
Console.ReadKey();
}
}
}
//使用API
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
class Program
{
[DllImport("kernel32.dll")]
public static extern void RtlMoveMemory(IntPtr Destination, ushort[] Source, int Length);
[DllImport("kernel32.dll")]
public static extern void RtlMoveMemory(ushort[] Destination, IntPtr Source, int Length);
static void Main(string[] args)
{
ushort[] uData = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };//ushort数组
IntPtr ptr = Marshal.AllocHGlobal(uData.Length * Marshal.SizeOf(typeof(ushort)));//分配内存
//拷贝
RtlMoveMemory(ptr, uData, uData.Length * sizeof(ushort));
//读取测试
ushort[] readData = new ushort[uData.Length];
//还原
RtlMoveMemory(readData, ptr, uData.Length * sizeof(ushort));
for (int i = 0; i < readData.Length; i++)
{
Console.Write(readData[i] + " ");
}
Marshal.FreeHGlobal(ptr);//用完以后释放内存
Console.ReadKey();
}
}
}
仅供参考
推荐于2017-09-06 · 知道合伙人互联网行家
关注
展开全部
对于ushort[],根本无需拷贝,可以直接获取
public static IntPtr GetPtrFromUShortArray(ushort[] value)
{
unsafe
{
fixed (ushort* pa = &value[0])
{
return new IntPtr(pa);
}
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
2014-03-29
展开全部
http://msdn.microsoft.com/zh-cn/library/vstudio/4ca6d5z7(v=vs.100).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
System.Runtime.InteropServices.Marshal.Copy
更多追问追答
追问
不能拷贝无符号吧的啊
只能拷贝有符号的
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询