本文主要是介绍C# 中IntPtr 与 string,数组互转,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、IntPtr 与 string互转
string str = "aa";
IntPtr init = Marshal.StringToHGlobalAnsi(str);
string ss= Marshal.PtrToStringAnsi(init);
//最后释放掉
Marshal.FreeHGlobal(init);
二、char*与string互转
string a = "11";
char* aChar = (char*)System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(a).ToPointer();
string result = Marshal.PtrToStringAnsi((IntPtr)aChar);
三、char* 与 IntPtr互转
可以直接强制类型转换
IntPtr init = (IntPtr)aChar;
char* aChar = (char*)init;
在c++里数据转指针是很容易的,但是在托管代码里,转起来就比较费劲了。转换方法如下:
- 1
internal static IntPtr ArrayToIntptr(byte[] source)
{
if (source == null)
return IntPtr.Zero;
unsafe
{
fixed (byte* point = source)
{
IntPtr ptr = new IntPtr(point);
return ptr;
}
}
}
internal static IntPtr ArrayToIntptr(byte[] source)
{
if (source == null)
return IntPtr.Zero;
byte[] da = source;
IntPtr ptr = Marshal.AllocHGlobal(da.Length);
Marshal.Copy(da, 0, ptr, da.Length);
return ptr;
}
如果不安全代码要用在.net里,只是在项目属性里,设置一下就行,但是要在unity里用的话就必须要加点东西了。
在unity里使用不安全代码时,要在Assetm目录下建一个smcs.rsp文件,在里边写一句-unsafe就行了,这个文件就是一个文本文件,然后改一下后缀名就行。
将数组转换为IntPtr
-
//第一种,使用不安全的代码块来访问直接指向字节数组的指针。 -
static IntPtr ArrayToIntptr(byte[] source) -
{ -
if (source == null) -
{ -
return IntPtr.Zero; -
} -
unsafe -
{ -
fixed (byte* point = source) -
{ -
IntPtr ptr = new IntPtr(point); -
return ptr; -
} -
} -
} -
//第二种,可以使用 GCHandle 来获得对象。 -
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 创建内存块并将数据封送处理到该内存块。 -
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); -
}
这篇关于C# 中IntPtr 与 string,数组互转的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!