简体   繁体   中英

How pass a structure containing a void* from c++ to c#?

I am having an issue and I can't find the answer on the net. I want to call a c++ function from my c# code. The c++ function is declared as:

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

with the following structure

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

In my c# code, I wrote:

 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);

I tried to run the code but it crashes so I guess I made a mistake with the structure specially the void* but I can't figure out what to put instead. It could also be the fact that the function returns an array of structure and maybe I am not calling it right. Could you help me with this? thanks a lot.

I have created a test application and the code is below and it is working fine...

// 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();
}

/ * ** * ** Output * ** * ** * * 10 Hi 50 20.23 * ** * ** * ** * ** * ** * ** * * /

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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