簡體   English   中英

封送結構數組指針的最佳方法

[英]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);

當我編譯它時,有一個例外:“無法封送'返回值':無效的托管/非托管類型組合。”

抱歉,編碼不正確...請幫助...

我試圖做完全相同的事情,但是由於時間不足而未能成功,但是我學到了一些東西:

  1. 在C#中分配內存
  2. 要傳遞結構數組,struct必須是blittable

祝你好運,我無法使其正常工作。

一個問題是編組器不知道C ++代碼返回的數組中有多少個項目。 一種替代方法是使用兩種C ++方法-一種返回項目數,一種返回給定索引的MainData。

在C#端,您的結構是什么樣的?

由於您同時在C ++和C#端進行編碼,因此使用C ++ / CLI而非PInvoke進行接口連接可能會更容易。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM