来自CSDN的一个结贴:http://topic.csdn.net/u/20081018/02/4472adae-063c-4ea7-a4fa-369614656339.html
如何将C#数组(如bytes[])传给具有IntPtr的托管代码函数?---非unsafe
问题:
我在C#里的数据存放在byte[]中,需要传到某一函数中去,如下:
byte[] byData = new byte[1024];
......对byData进行赋值
// 完毕后,将该数组中的数据传给该函数,该函数声明如下
MyFunction(int iNo, IntPtr pData, uint nDataSizeinBytes);
// 该函数原形声明中的pData就是用来存贮数据的
解决方法:
1:先申请一段非托管的内存空间,使用的方法是:
-
C# code
-
IntPtr System.Runtime.InteropServices.Marshal.AllocHGlobal( int size); IntPtr hglobal = System.Runtime.InteropServices.Marshal.AllocHGlobal( 100 );
该函数传入一个你要申请的空间大小,返回申请到的非托管内存指针hglobal。
2:把你的数据从byte[]复制到这段内存空间中。
复制字节流所使用的方法是:
-
C# code
-
[SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] public static void System.Runtime.InteropServices.Marshal.Copy( byte [] source, int startIndex, IntPtr destination, int length ) // 示例 System.Runtime.InteropServices.Marshal.Copy(byData, 0 ,hglobal,byData.Length);
3:把步骤1取得的指针传入你的非托管函数中。
-
C# code
-
MyFunction(iNo, hglobal,byData.Length);
注意:
非托管内存需要自行释放。你可以选择在托管程序(C#)中释放,方法是:
Marshal.FreeHGlobal(hglobal);
如果你在C#中释放需要采用一种机制来由你的函数通知C#程序内存已经使用完成,不然将会造成不小的风险。
当然你也可以在非托管的程序中释放,这就要看你的程序是否已经实现了释放或者可以修改。
MSDN的一个页面地址,中文的。
http://msdn.microsoft.com/zh-cn/magazine/cc164193.aspx