I want to convert a byte*
to a byte[]
, but I also want to have a reusable function to do this:
public unsafe static T[] Create<T>(T* ptr, int length)
{
T[] array = new T[length];
for (int i = 0; i < length; i++)
array[i] = ptr[i];
return array;
}
Unfortunately I get a compiler error because T might be a ".NET managed type" and we can't have pointers to those. Even more frustrating is that there is no generic type constraint which can restrict T to "unmanaged types". Is there a built-in .NET function to do this? Any ideas?
Seems that the question becomes: How to specify a generic Type to be a simple type.
Gives the error:
Cannot take the address of, get the size of, or declare a pointer to a managed type ('T')
The method that could match what you are trying to do is Marshal.Copy, but it does not take the appropriate parameters to make a generic method.
Although there it is not possible to write a generic method with generic constraints that could describe what is possible, not every type can be allowed to be copied using an "unsafe" way. There are some exceptions; classes are one of these.
Here is a sample code:
The method can be generic, but it cannot take a pointer of a generic type. This is not an issue since pointers covariance is helping, but this has the unfortunate effect of preventing an implicit resolution of the generic argument type. You then have to specify MakeArray explicitly.
I've added a special case for the structures, where it is best to have types that specify a struct layout. This might not be an issue in your case, but if the pointer data is coming from native C or C++ code, specifying a layout kind is important (The CLR might choose to reorder fields to have a better memory alignment).
But if the pointer is coming exclusively from data generated by managed code, then you can remove the check.
Also, if the performance is an issue, there are better algorithms to copy the data than doing it byte by byte. (See the countless implementations of memcpy for reference)
I have no idea whatsoever if the following would work, but it might (at least it compiles :):
The key is to use
Marshal.PtrToStructure
to convert to the correct type.How about this?
We can't use sizeof(T) here, but the caller can do something like