簡體   English   中英

如何構造一個結構數組的指針

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

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

抱歉編碼不好...請幫忙......

  • 首先,您需要記住,返回值的MarshalAs(顯式或隱式)實質上意味着“將本機結構內容復制到托管結構中”。
  • 其次,由於CLR封送器只復制數據,如果你沒有釋放你在C ++函數中分配的內存,你就會有內存泄漏需要管理。
  • 第三,這個錯誤主要是由於CLR封送程序無法知道本機代碼返回的數組的長度這一事實,因為你基本上是返回一個內存指針而沒有長度。

如果你想保持這些內存結構,我強烈建議你研究一下C ++ / CLI。 您將能夠將這些復雜類型包裝到混合的本機/托管類中,從而避免復制數據。 這將幫助您將本地和托管代碼之間的數據編組保持在最低限度。

如果您仍然想要使用C#而不是C ++ / CLI,則必須編寫一些更智能的代碼來將本機代碼返回的數據解組為托管數據。 您可以查看Custom Marshaling

我沒有看到.NET運行時如何知道在GetData(...)中分配了多少MainData

重構您的C ++代碼以使用數組來填充或返回單個MainData

暫無
暫無

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

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