How to correctly pass a buffer array pointer to unmanaged dll from C#

0

I have a function in an unmanaged library that looks like this:

void fill_arr(int size, struct mystruct **buffer)
{
  /* code that allocates memory for size number of structs and fills the pointer buffer */
}

In C# i try to do the following:

[DllImport("mylib.dll", CallingConvention = CallingConvention.Winapi, EntryPoint = "fill_arr", CharSet = CharSet.Ansi)]
static extern void fill_arr(int count, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] ref c_struct[] result);

public static MyObject[] InitObjects(int count)
{
  c_struct[] c_buffer = new c_struct[count];
  MyManagedObject[] result = new MyManagedObject[count];

  fill_arr(count, ref c_buffer);
  for (int i = 0; i < count; i++)
    result[i] = new MyManagedObject(ref c_buffer [i]);

  return result;
}

MyManagedObject is a wrapper for c_struct that assigns c_struct to a private variable and has several methods to work with the c_struct data

However when i try to run this method, i get a CLR error 0x80131506 at System.StubHelpers.MngdNativeArrayMarshaler.ConvertSpaceToManaged(IntPtr, System.Object ByRef, IntPtr, Int32). What am i doing wrong and what would be the correct way to fill the struct buffer?

c#
marshalling
asked on Stack Overflow Sep 11, 2020 by JustClaire • edited Sep 11, 2020 by bk_32

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0