C # - create a managed array from a pointer

I am trying to create a managed array of twins from an array of bytes. I have a problem right now, but I want to optimize. Here is some code that I would like to work:

private unsafe static double[] _Get_Doubles(byte[] _raw_data) { double[] ret; fixed (byte* _pd = _raw_data) { double* _pret = (double*)_pd; ret = (double[])*_pret; //FAILURE } } 

Please let me know how to deal with these problems.

-Aaron

+7
arrays pointers managed unmanaged
source share
2 answers

Just now, I thought stackalloc would be correct, but it fails. Most importantly, now I know that he is doomed to failure. It is impossible to do what I want to do.

This can be seen by asking:

How to create a managed array around an "unsafe" array?

Since the managed array has header information (because it is a class around the memory cartridge), it requires more memory space than the array itself. So the answer is:

Allocate space before (and / or after? Depending on how the managed arrays are stored in memory) the array itself and place the managed information (length, (and so on)) around the "unsafe" array.

This is not easy, because to provide enough data around the array is unstable at best. In my specific example, there may be enough space for it, because the managed byte [] is transmitted in the sense that there is data around the array, but to argue that the same data is suitable for the managed double [] is doubtful at best, but most probably erroneous, and modifying the data to make it suitable for managed double [] is vile.

[EDIT]

Marshal.Copy to be the way to go here. Create a new array and let the marshal copy them (hoping that it will be faster than me or, possibly, at a later date, it will be faster):

 var ret = new double[_raw_data.Length / sizeof(double)]; System.Runtime.InteropServices.Marshal.Copy(new System.IntPtr(_pret), ret, 0, ret.Length); 
+2
source share

One of the key points to notice about the code you posted is that there is no way to find out how many positions the return value is indicated, and the managed array should know how big it is. You can return double* or create new double[XXX] and copy the values ​​or even (if the counter is constant) create a struct with the member public fixed double _data[2]; and pass raw data to this type.

+3
source share

All Articles