如何将包含void*的结构体从c++传递到c#

本文关键字:c++ 结构体 包含 void | 更新日期: 2023-09-27 18:18:57

我有一个问题,我在网上找不到答案。我想从c#代码中调用一个c++函数。c++函数声明为:

int read(InfoStruct *pInfo, int size, BOOL flag)

与以下结构

typedef struct
{
    int ID; 
    char Name[20];
    double value;
    void *Pointer;
    int time;
}InfoStruct;

在我的c#代码中,我写:

 public unsafe struct InfoStruct
 {
    public Int32 ID;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]
    public string Name;
    public Double value;
    public void *Pointer;
    public Int32 time;
  };
[DllImport("mydll.dll", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl)]
        public static extern unsafe int read(out MeasurementInfoStruct[] pInfo, int size, bool flag);

我试着运行代码,但它崩溃了,所以我想我犯了一个错误的结构,特别是void*,但我不知道该放什么代替。它也可能是函数返回一个数组结构,也许我没有正确调用它。你能帮我一下吗?非常感谢。

如何将包含void*的结构体从c++传递到c#

我已经创建了一个测试应用程序,代码如下,它工作正常…

// CPP code
typedef struct
{
    int ID; 
    char Name[20];
    double value;
    void *Pointer;
    int time;
}InfoStruct;
int WINAPI ModifyListOfControls(InfoStruct *pInfo, int size, bool flag)
{
    int temp = 10;
    pInfo->ID = 10;
    strcpy(pInfo->Name,"Hi");
    pInfo->value = 20.23;
    pInfo->Pointer = (void *)&temp;
    pInfo->time = 50;
    return 0;
}
/***************************************************/
// This is C# code
[StructLayout(LayoutKind.Sequential)]
public struct InfoStruct
{
    public Int32 ID;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]
    public string Name;
    public Double value;
    public IntPtr Pointer;
    public Int32 time;
};

[DllImport(@"D:'Test'Projects'Release_Build'WeldDll.dll", CallingConvention = CallingConvention.Winapi)]
public static extern int ModifyListOfControls(ref InfoStruct pInfo, int size, bool flag);// ref InfoStruct pi);
public static void Main()
{
    InfoStruct temp = new InfoStruct();
    temp.Pointer = new IntPtr();
    ModifyListOfControls(ref temp, 200, true);
    Console.WriteLine(temp.ID);
    Console.WriteLine(temp.Name);
    Console.WriteLine(temp.time);
    Console.WriteLine(temp.value);

    Console.ReadLine();
}

/ * * * * * * 输出 * * * * * * * * 10嗨5020.23 * * * * * * * * * * * * * * * * * * /