views:

323

answers:

3

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.

My C++ codes:

// 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#?

My current codes in C# are:

[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...

+1  A: 

Try looking here, it seemed to have some possible fixes.

zipcodeman
A: 

One problem is that the marshaller doesn't know how many items are in the array returned by the C++ code. 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.

What do your structures look like on the C# side?

Since you are coding both the C++ and C# side, it may be easier to use C++/CLI to interface them instead of PInvoke.

Saxon Druce
A: 

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#
  2. To pass array of structs, struct must be blittable.

Good luck with that, I couldn't make it to work.

TheBlack