[英]Best Way To Marshal A Pointer of Array of Struct
我正在從C ++調用函數,該函數返回指向struct數組的指針,由於遇到了這種操作/實現,我遇到了問題。
我的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);
當我編譯它時,有一個例外:“無法封送'返回值':無效的托管/非托管類型組合。”
抱歉,編碼不正確...請幫助...
一個問題是編組器不知道C ++代碼返回的數組中有多少個項目。 一種替代方法是使用兩種C ++方法-一種返回項目數,一種返回給定索引的MainData。
在C#端,您的結構是什么樣的?
由於您同時在C ++和C#端進行編碼,因此使用C ++ / CLI而非PInvoke進行接口連接可能會更容易。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.