c# byte[] 转换为 IntPtr几种方法
来源:互联网 发布:win7安装数据库没反应 编辑:程序博客网 时间:2024/06/05 19:23
有几种方法可以访问与字节数组相对应的 IntPtr。
第一种,使用不安全的代码块来访问直接指向字节数组的指针。
代码如下 复制代码
unsafe
{
byte[] test = newbyte[5];
fixed (byte* p = &test[0])
{
*p = 0xff;
}
}
第二种,可以使用 GCHandle 来获得对象。
代码如下 复制代码
using System.Runtime.InteropServices;
byte[] test = new byte[5];
GCHandle hObject = GCHandle.Alloc(test, GCHandleType.Pinned);
IntPtr pObject = hObject.AddrOfPinnedObject();
if(hObject.IsAllocated)
hObject.Free();
第三种, 通过 LocalAlloc 创建内存块并将数据封送处理到该内存块。
代码如下 复制代码
[DllImport(coredll.dll,SetLastError=true)]
public static extern IntPtr LocalAlloc(uint uFlags, uint uBytes);
[DllImport(coredll.dll,SetLastError=true)]
public static extern IntPtr LocalFree(IntPtr hMem);
[DllImport(coredll.dll,SetLastError=true)]
public static extern IntPtr LocalReAlloc(IntPtr hMem, uint uBytes, uint fuFlags);
public const uint LMEM_FIXED = 0;
public const uint LMEM_MOVEABLE = 2;
public const uint LMEM_ZEROINIT = 0x0040;
byte[] test = new byte[5];
IntPtr p = LocalAlloc(LMEM_FIXED | LMEM_ZEROINIT, (uint)test.Length);
if (p == IntPtr.Zero)
{
throw new OutOfMemoryException();
}
else
{
Marshal.Copy(test, 0, p, test.Length);
}
using System;
using System.Runtime.InteropServices;
class Example
{
static void Main()
{
// Create a managed array.
byte[] managedArray = { 1, 2, 3, 4 };
// Initialize unmanaged memory to hold the array.
int size = Marshal.SizeOf(managedArray[0]) * managedArray.Length;
IntPtr pnt = Marshal.AllocHGlobal(size);
try
{
// Copy the array to unmanaged memory.
Marshal.Copy(managedArray, 0, pnt, managedArray.Length);
// Copy the unmanaged array back to another managed array.
byte[] managedArray2 = new byte[managedArray.Length];
Marshal.Copy(pnt, managedArray2, 0, managedArray.Length);
Console.WriteLine("The array was copied to unmanaged memory and back.");
}
finally
{
// Free the unmanaged memory.
Marshal.FreeHGlobal(pnt);
}
}
}
- c# byte[] 转换为 IntPtr几种方法
- asp.net中c# byte[] 转换为 IntPtr几种方法
- 将IntPtr转化为byte[]
- (转)C#进行图像处理的几种方法(bitmap,bitmapData,IntPtr)
- C#进行图像处理的几种方法(bitmap,bitmapData,IntPtr)
- 从图像转换到byte[]数组的几种方法
- 从图像转换到byte[]数组的几种方法
- C# 将byte[] 转换为 string
- C# int 转换为byte 的浅析
- c# byte数组转换为字符串
- C# Int 和 IntPtr 互相转换
- 在C# 中将byte转换为int和int转换为byte
- int/byte/byte[]转换 c#
- 在C# 中将byte[]转换为int和int转换为byte[] 将字符串转byte[]以及反向转
- 几种字符串到byte[] 数组转化为String 的方法
- 几种字符串到byte[] 数组转化为String 的方法
- 在C#中如何使用BYTE[]转换为String
- C#中将byte数组转换为8bit灰度图像
- fastjson序列化时去掉null字段
- 判断字段里是否含字母
- Leetcode: Shortest Distance from All Buildings
- __attribute__((visibility("default")))
- Eclipse插件Osgi
- c# byte[] 转换为 IntPtr几种方法
- 2015 移动技术白皮书
- JSON.stringify(),eval(),JSON.parse()
- 天声人語 20160105 「申」という字の来歴
- 关系型数据库管理系统简介
- spark源码阅读1
- Android.mk详解
- jqGrid增删改查显示——增加+nodejs后台
- Instancetype与id的区别和联系