2014-01-05 34 views
2

獲得雙數組值具有雙陣列,我可以將其轉換爲IntPtr的與反向的方式從IntPtr的

public static IntPtr DoubleArrayToIntPtr(double[] d) 
{ 
    IntPtr p = Marshal.AllocCoTaskMem(sizeof(double) * d.Length); 
    Marshal.Copy(d, 0, p, d.Length); 
    return p; 
} 

現在的場景,我只能從IntPtr的一些功能「用GetPoint」獲得數組值是時尚,我怎麼能從IntPtr檢索雙數組值?

例如,下面的示例中假設path是數據集,其具有(ID,X,Y,Z)的結構,保持5點的座標等

(1, 10,10,0) 
(2, 8 ,10,0) 
(3, 9 ,50,0) 
(4, 70,40,0) 
(5, 60,60,0) 

所以我想從IntPtr的雙數組的值「一」從功能

我試圖像:

for(int i = 0; i < path.GetNumberOfPoints(); i++) //this does loop five times 
{ 
    double[] pastPoints = new double[4]; //id,x,y,z 
    IntPtr a = DoubleArrayToIntPtr(pastPoints); 
    path.GetPoint(i, a); 
    System.Console.WriteLine(pastPoints[0]); 
    System.Console.WriteLine(pastPoints[1]); 
    System.Console.WriteLine(pastPoints[2]); 
    System.Console.WriteLine(pastPoints[3]); 
} 

,但只得到0的,什麼是我做錯了什麼?

+0

該代碼只會工作。 – sisve

+0

答案在於這個問題:'Marshal.Copy' –

回答

1

我對元帥沒有任何經驗,但是我有一些來自C++日子的經驗。

我希望你想這樣做:如果path.GetPoint實際上寫的數據,這些內存地址,我猜它不

double[] pastPoints = new double[4]; //id,x,y,z 
IntPtr a = Marshal.AllocCoTaskMem(sizeof(double) * pastPoints.Length); // Allocate memory for result 
path.GetPoint(i, a); // Generate result. 
Marshal.Copy(a, pastPoints, 0, pastPoints.Length); // Copy result to array. 
Marshal.FreeCoTaskMem(a); 

System.Console.WriteLine(pastPoints[0]); 
System.Console.WriteLine(pastPoints[1]); 
System.Console.WriteLine(pastPoints[2]); 
System.Console.WriteLine(pastPoints[3]); 
+0

你是如此的非常正確!謝謝 – cMinor