2016-02-24 180 views
1

我需要從非託管代碼中獲取值C。其實我從unmanaged調用函數,函數的返回類型是點,其中點是一個結構。從非託管代碼獲取值到託管代碼

結構提到以下方式

typedef struct point 
{ 
    Poly* pol; 
    NL_DEGREE p; 
    VECTOR* vec; 
} Point; 

PolyVECTOR是結構。

其實我得到的返回值點作爲IntPtrC#。之後獲得的IntPtr的價值,我想這Intptr轉換爲Array。按照以下方式轉換Array

point[] Q = new point[2]; 
int size= Marshal.SizeOf(new point()); 
for (int i = 0; i < 2; i++) 
{ 
    Q[i] = (point)Marshal.PtrToStructure(new IntPtr(Qptr.ToInt32() + (i * size)), typeof(point)); 
} 

但是,得到的陣列中的每個結構元素的值成爲null.What我發錯了這一點,請任何人建議我以後......

我提到在C#創建detaily結構下面。

public unsafe struct point 
     { 
      public Poly* pol; 
      public NL_DEGREE p; 
      public vECTOR* knt; 
     } 

其中聚

public unsafe struct Poly 
     { 
      public Int32 n; 
      public cpoint* Pw; 
     } 

COINT也是一個結構

public struct cpoint 
     { 
      public double x; 
      public double y; 
      public double z; 
      public double w; 
     } 

其中VECTOR

public unsafe struct VECTOR 
     {    
      public Int32 m; 
      public double *U;   

     } 

回答

0

從你的代碼片斷還不清楚結構究竟怎麼用C定義假設一些默認對齊彪你的C#的定義應該是這樣的:

public class Point 
{ 
    IntPtr pol; 
    NL_DEGREE  p; 
    IntPtr vec; 
} 

你還是要考慮確切的結構佈局與適當的包裝規格(見1瞭解詳細信息)

所以在你的代碼,你就必須做到以下幾點:

var point = (Point)Marshal.PtrToStructure(ptr, typeof(Point)); 
var poly = (Poly)Marshal.PtrToStructure(point.pol, typeof(Poly)); 
var vector = (Vector)Marshal.PtrToStructure(point.vec, typeof(Vector)); 

因爲這兩個保利和Vector可能是你可能希望使用IntPtr.Add()2方法來遍歷這些陣列陣列。

StructLayoutAttribute.Pack Field

IntPtr.Add

+0

感謝回答,我已經把結構這在C#創建在同一職位編輯的細節 – Shankar