Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

managed array of pointers in c#

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?

like image 917
Nikita Avatar asked May 10 '26 01:05

Nikita


1 Answers

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.

like image 52
Fabjan Avatar answered May 11 '26 14:05

Fabjan