2010-01-14 42 views
1

我從C++調用函數返回一個指向結構數組的指針,我有問題,因爲我是這個操作/實現的新手。最好的方法來元帥結構數組的指針

我的C++代碼:

// My C++ Structs 
typedef struct _MainData { 
double dCount; 
DataS1   *DS1; 
int iCount1; 
DataS2   *DS2; 
int iCount2; 
}MainData; 

typedef struct _DataS1 { 

unsigned int uiCount1; 
unsigned int uiCount2; 
int iCount; 
void *pA; 
void *pB; 

} DataS1; 

typedef struct _DataS2 { 
unsigned int uiCount1; 
unsigned int uiCount2;  
unsigned int uiCount3;  
unsigned int uiCount4; 
double dCount; 
int iCount1;  
char strLbl[64]; 
} DataS2; 

// My C++ Function 
MainData* GetData(const int ID) 
{ 
     MainData* mData; 
     int iLength = Get_Count(); 
     mData = new MainData[iLength]; 
     for(int x = 0;x < VarCounter; x++) 
     { 
      // Codes here assign data to mData[x] 
     } 
     return mData; 
} 

問: 我怎麼能調用C++函數的GetData到C#?

我在C#當前代碼:

[DllImport(".\\sdata.dll")] 
[return: MarshalAs(UnmanagedType.LPArray)] 
private static unsafe extern MainData[] GetData(int ID); 

// The struct MainData in my C# side is already "Marshalled"... 

//My function call is here: 
MainData[] SmpMapData = GetData(ID); 

當我編譯它,有一個例外: 「不能元帥‘返回值’:無效的託管/非託管類型組合。」

對不起,糟糕的編碼......請幫助...

回答

-1

一個問題是,編組不知道有多少項目是由C++代碼返回在數組中。另一種方法可以是擁有兩個C++方法 - 一個返回項目數,另一個返回給定索引的單個MainData。

你的結構在C#端看起來像什麼?

由於您正在編寫C++和C#端的代碼,因此使用C++/CLI來連接它們可能更容易,而不是使用PInvoke。

0

我試圖做同樣的事情,但由於時間不夠沒能成功,但我學會了在處理事情:

  1. 在C#中分配內存
  2. 要通過結構的數組,結構必須是blittable

祝你好運,我無法讓它工作。