Search code examples
c#c++pinvoke

p/invoke method returns empty struct


I have C++ code that contains a struct and I need to pass it to C#:

wrapper.h

#pragma once
typedef struct
{
    int     int1;
    int     int2;
} MY_STRUCT;

MY_STRUCT mystruct;
extern "C" __declspec(dllexport) int __stdcall GetTestStruct(MY_STRUCT* cs_struct);

wrapper.cpp:

int __stdcall GetTestStruct(MY_STRUCT* cs_struct)
{
    mystruct.int1 = 23;
    mystruct.int2 = 45;
    cs_struct = &mystruct;
    return 0;
}

wrapper.cs:

class Program
{
  [StructLayout(LayoutKind.Sequential)]
  public struct MY_STRUCT
  {
    public int int1;
    public int int2;
  }

  [DllImport(VpxMctlPath)]
  public static extern int GetTestStruct(ref MY_STRUCT mystruct);

  static void Main(string[] args)
  {
    var s = new MY_STRUCT();
    GetTestStruct(ref s);
  }
}

After I run this code, s still has zeros for int1 and int2. I've tried to make the C# struct fields private and public, but no difference. I looked at C++/CLI, but that seems overkill for this small task. Is there a simple way to do this?


Solution

  • Change your C++ function to set the integer values directly on the referenced struct:

    int __stdcall GetTestStruct(MY_STRUCT* cs_struct)
    {
        cs_struct->int1 = 23;
        cs_struct->int2 = 45;
        //cs_struct = *mystruct; //This line may not be necessary
        return 0;
    }