There are many examples over the net how to get pointer to byte[]
or int[,]
, i.e. when you know exactly the element type and rank of the array. But how to get the pointer for generic Array
?
The main problem here is I don't know rank in the advance. I don't know element type too but I know there can be only primitive numeric type (in my case), so I could type few extra if
s to cope with it.
Background: I would like to make this solution https://stackoverflow.com/a/52750659/6734314 more general -- in its current form it works only with double[,]
so classic rank+type is given:
double[,] doubles = {
{ 1, 2, 3, 4 },
...
};
fixed (double* p = doubles)
{
...
First attempt
From Olivier answer, all mistakes are mine.
Array data = new float[,] { { 4, 2 }, { 77, 3 } };
var reference = __makeref(data);
IntPtr pointer = **(IntPtr**)(&reference);
float* ptr = (float*)pointer.ToPointer();
{
for (int i = 0; i < data.LongLength; ++i)
Console.WriteLine(ptr[i]);
}