c# - 编码结构数组指针的最佳方法

标签 c# c++ struct pointers marshalling

我正在从 C++ 调用函数,该函数返回一个指向结构数组的指针,我遇到了问题,因为我是这个操作/实现的新手。

我的 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. 要传递结构数组,结构必须是blittable .

祝你好运,我没能成功。

关于c# - 编码结构数组指针的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2061821/

相关文章:

android - all-proto-files-under 不适用于 android.mk

arrays - 我可以使用什么结构来解码字符串数组的JSON数组?

c - 为什么通过 typedef-ed 指针访问 struct 的字段不起作用?

c# - C#中的类和基类继承

c++ - 用于桌面 Gui 应用程序的 Qt 4.x/5.x 和 OpenGL : What module to choose?

c# - 如何让搜索栏输入搜索同时包含大写字母和小写字母的字符串而不更改字符串文本

c++ - 使用链表在 C++ 中实现邻接表

c - 难以理解 MPI_Type_create_struct

c# - Parallel.For 循环相同的项目

c# - LinqKit Predicate Builder 抛出 TypeLoadException?