C#訪問C++動態分配的數組指針


項目中遇到C#調用C++算法庫的情況,C++內部運算結果返回矩形坐標數組(事先長度未知且不可預計),下面方法適用於訪問C++內部分配的任何結構體類型數組。當時想當然的用ref array[]傳遞參數,能計算能分配,但是在C#里只得到arr長度是1,無法訪問后續數組Item。
==========================================================================
C++
==========================================================================
接口示例:

1 void Call(int *count, Rect **arr)
2 {
3     //…..
4     //重新Malloc一段內存,指針復制給入參,外部調用前並不知道長度,另外提供接口Free內存
5     //….
6 }

結構體:

1 Struct Rect
2 {
3 int x;
4 int y;
5 int width;
6 int height;
7 };

========================================================================
C#:
========================================================================
結構體:

1 Struct Rect
2 {
3 public int x;
4 public int y;
5 public int width;
6 public int height;
7 }

 


外部DLL方法聲明:

1 [DllImport("xxx.dll", EntryPoint = "Call", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
2 public static extern void Call(
3                 ref int count,
4                 ref IntPtr pArray);

方法調用:

1 IntPtr pArray = IntPtr.Zero; //數組指針
2 int count = 0;
3 Call(ref count, ref pArray);
4 var rects = new Rect[count]; //結果數組
5 for (int i = 0; i < count; i++)
6 {
7 var itemptr = (IntPtr)((Int64)Rect + i * Marshal.SizeOf(typeof(Rect))); //這里有人用的UInt32,我用的時候溢出了,換成Int64
8 rects[i] = (Rect)Marshal.PtrToStructure(itemptr, typeof(Rect));
9 }

========================================================================
參考鏈接:http://blog.csdn.net/wumuzhizi/article/details/48180167

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM