简体   繁体   English

封送结构数组指针的最佳方法

[英]Best Way To Marshal A Pointer of Array of Struct

I'm calling functions from C++ that returns a pointer to an array of struct and I'm having problems since I'm new to this operation/implementation. 我正在从C ++调用函数,该函数返回指向struct数组的指针,由于遇到了这种操作/实现,我遇到了问题。

My C++ codes: 我的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;
}

Question: How can I call the C++ function GetData to C#? 问题:如何将C ++函数GetData调用为C#?

My current codes in C# are: 我目前在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);

When I compiled it, there's an exception: "Cannot marshal 'return value': Invalid managed/unmanaged type combination." 当我编译它时,有一个例外:“无法封送'返回值':无效的托管/非托管类型组合。”

Sorry for the poor coding... Please help... 抱歉,编码不正确...请帮助...

I tried to do exactly the same thing but didn't succeed due to lack of time but I learned something in process: 我试图做完全相同的事情,但是由于时间不足而未能成功,但是我学到了一些东西:

  1. Allocate memory in C# 在C#中分配内存
  2. To pass array of structs, struct must be blittable . 要传递结构数组,struct必须是blittable

Good luck with that, I couldn't make it to work. 祝你好运,我无法使其正常工作。

One problem is that the marshaller doesn't know how many items are in the array returned by the C++ code. 一个问题是编组器不知道C ++代码返回的数组中有多少个项目。 An alternative approach could be to have two C++ methods - one which returns the number of items, and one which returns a single MainData given an index. 一种替代方法是使用两种C ++方法-一种返回项目数,一种返回给定索引的MainData。

What do your structures look like on the C# side? 在C#端,您的结构是什么样的?

Since you are coding both the C++ and C# side, it may be easier to use C++/CLI to interface them instead of PInvoke. 由于您同时在C ++和C#端进行编码,因此使用C ++ / CLI而非PInvoke进行接口连接可能会更容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM