Home > database >  Pass array from C# to C
Pass array from C# to C

Time:07-06

I am trying to pass an array from C# to a C DLL and then print it from C .

The C# code is the following:

[DllImport("DLL1.dll", CallingConvention = CallingConvention.StdCall)]
public static extern void GMSH_PassVector([MarshalAs(UnmanagedType.SafeArray,SafeArraySubType = VarEnum.VT_I4)] int[] curveTag);

int[] curveTagArray = { 1, 2, 3, 4 };
GMSH_PassVector(curveTagArray);

The C header file code is the following:

extern "C" GMSH_API  void GMSH_PassVector(std::vector<int> *curveTags);

The C cpp file code is the following to display the first element of the array:

void GMSH_PassVector(std::vector<int> *curveTags)
{
    printf("Hello %d \n", curveTags[0]);
}

Seems that I'm doing something wrong, a value is displayed but it is the wrong one.

CodePudding user response:

I don't think the marshal mechanism is able to translate a int[] to a std::vector. It's better to use language base types. Change the C function as

void GMSH_PassVector(int * arr, int size)

and in C# you have to instantiate a IntPtr to hold the address of the first element of the array.

int bufferSize = 4;
int[] buffer = new int[bufferSize];

buffer[0] = 1;
buffer[1] = 2;
buffer[2] = 3;
buffer[3] = 4;

int size = Marshal.SizeOf(buffer[0]) * buffer.Length;
IntPtr bufferPtr = Marshal.AllocHGlobal(size);
Marshal.Copy(buffer, 0, bufferPtr, size);

GMSH_PassVector(bufferPtr, size);

Marshal.FreeHGlobal(bufferPtr);
  •  Tags:  
  • c# c
  • Related