
First: the above C++ is not a 2D array, but an array of arrays !
I seems as if .NET does not want to marshal an array of arrays
automatically.
So the only solution I can come up with is the rather complex
code attached below.
Arne
===============================================
__declspec(dllexport) void f(float **x, int n, int m)
{
int i, j;
for(i = 0; i < n; i++)
{
for(j = 0; j < m; j++) printf(" %8.2f", x[i][j]);
printf("\n");
}
}
using System;
using System.Runtime.InteropServices;
namespace E
{
public class Program
{
[DllImport(@"C:\twodim.dll")]
private static extern void f(IntPtr x, int n, int m);
private static IntPtr UMC(float[][] x, int n, int m)
{
IntPtr[] slice = new IntPtr[n];
for(int i = 0; i < n; i++)
{
slice[i] = Marshal.AllocHGlobal(m * sizeof(float));
Marshal.Copy(x[i], 0, slice[i], m);
}
IntPtr res = Marshal.AllocHGlobal(n *
Marshal.SizeOf(typeof(IntPtr)));
Marshal.Copy(slice, 0, res, 3);
return res;
}
private static void UMD(IntPtr x, int n, int m)
{
IntPtr[] slice = new IntPtr[n];
Marshal.Copy(x, slice, 0, n);
for(int i = 0; i < n; i++)
{
Marshal.FreeHGlobal(slice[i]);
}
Marshal.FreeHGlobal(x);
}
public static void Main(string[] args)
{
float[][] x = new float[3][];
for(int i = 0; i < 3; i++)
{
x[i] = new float[2];
for(int j = 0; j < 2; j++)
{
x[i][j] = (i + 1) * 10 + (j + 1);
}
}
IntPtr umx = UMC(x, 3, 2);
f(umx, 3, 2);
UMD(umx, 3, 2);
Console.ReadKey();
}
}
}