I have a trouble creating managed array of pointers.
I've tried
public unsafe class Car
{
public int speed;
public Car()
{
speed = 0;
}
public Car(int speed)
{
this.speed = speed;
}
}
class Program
{
public static unsafe void Main(string[] args)
{
var arr = new Car[10]; // 1st way
fixed(Car* ptr = arr)
{}
Car* arr = stackalloc Car[10]; // 2nd way
}
}
After both tries I get the same error: "Impossible to get adress or size or define a pointer of managed type". Does somebody know how to fix it?
Well, as C# specs say:
Unlike references (values of reference types), pointers are not tracked by the garbage collector—the garbage collector has no knowledge of pointers and the data to which they point.
For this reason a pointer is not permitted to point to a reference or to a struct that contains references, and the referent type of a pointer must be an unmanaged-type. An unmanaged-type is any type that isn’t a reference-type and doesn’t contain reference-type fields at any level of nesting. In other words, an unmanaged-type is one of the following:
sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool.
Any enum-type.
Any pointer-type. Any user-defined struct-type that contains fields of unmanaged-types only.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With