I have an array allocated in C#
which I am passing into unmanaged code to be modified. The following code works, but I am not sure if there are any other more 'correct' or 'efficient' methods that I am not aware of.
Code.c
extern "C" {
class MyObject
{
public:
int32_t X;
};
__declspec(dllexport) void ArrayTest(MyObject* a, int length);
void ArrayTest(MyObject* a, int length)
{
for (int i = 0; i < length; i++)
{
a[i].X = i + 1;
}
}
}
Code.cs
class Program
{
[StructLayout(LayoutKind.Sequential)]
public struct MyObject
{
public Int32 X;
}
[DllImport(@"MyDll.dll", CallingConvention = CallingConvention.Cdecl)]
public extern static void ArrayTest(IntPtr objects, int length);
static void Main(string[] args)
{
var objects = new MyObject[3];
var handle = GCHandle.Alloc(objects, GCHandleType.Pinned);
var ptr = GCHandle.ToIntPtr(handle);
ArrayTest(ptr, objects.Length);
for (int i = 0; i < objects.Length; i++)
{
var offset = Marshal.SizeOf<MyObject>() * i;
objects[i] = Marshal.PtrToStructure<MyObject>(IntPtr.Add(ptr, offset));
}
}
}
extern "C" class
? C only hasstruct
. \$\endgroup\$