0

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.

2
  • Does this answer your question? How to pass C# array to C++ and return it back to C# with additional items? Commented Jul 5, 2022 at 6:27
  • 1
    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. Commented Jul 5, 2022 at 6:32

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.