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