I'm trying to make an Array of pointers to be able to track the reference to any unmanage object added to it and change it, but the behaviour is different when I create an Pointer Array of Int and when create a Pointer Array of Persons what is unmanaged.
public unsafe struct Person
{
public char* name;
public int age;
public Person(string name, int age)
{
this.name = (char*)Marshal.StringToCoTaskMemAuto(name);
this.age = age;
}
}
For add:
public static unsafe void WriteValueAtPointerArrayIndex<T>(ref T** pointerArray, int index, in T value) where T : unmanaged
{
T** ptr = pointerArray;
fixed (T* ptrValue = &value)
{
ptr += index;
*ptr = ptrValue;
Console.WriteLine("Address where add: {0}, Value: {1}", (long)ptr, **ptr);
}
}
For get:
public static unsafe ref T* GetPointerValueAtPointerArrayIndex<T>(ref T** pointerArray, int index) where T : unmanaged
{
T** ptr = pointerArray;
ptr += index;
ref T* value = ref *ptr;
Console.WriteLine("Address to return: {0}, Value {1}", (long)ptr, *value);
return ref value;
}
Using the methods:
UnsafeList use the methods inside and create the internal Array using:
T**_Array = (T**)Marshal.AllocHGlobal(Marshal.SizeOf<T>() * _Capacity);
where T: unmanaged (new feature of .NET 4.7.3)
UnsafeList<int> list = new UnsafeList<int>(10);
list.Add(10);
list.Add(14);
list.Add(20);
list.Add(25);
list.Add(30);
for(int i = 0; i < list.Length; i++)
{
var v = list[i];
}
Using it with Person:
UnsafeList<Person> persons = new UnsafeList<Person>(10);
Person miguel = new Person("Miguel", 23);
Person elena = new Person("Elena", 24);
Person ana = new Person("Ana", 34);
Person ulises = new Person("Ulises", 23);
persons.Add(miguel);
persons.Add(elena);
persons.Add(ana);
persons.Add(ulises);
for (int i = 0; i < persons.Length; i++)
{
var v = persons[i];
}
Results:
For ints:
Address where add: 2151492103952, Value: 10 Address where add: 2151492103960, Value: 14 Address where add: 2151492103968, Value: 20 Address where add: 2151492103976, Value: 25 Address where add: 2151492103984, Value: 30
///Here only returns the last added but all the address are correct
Address to return: 2151492103952, Value 30
Address to return: 2151492103960, Value 30
Address to return: 2151492103968, Value 30
Address to return: 2151492103976, Value 30
Address to return: 2151492103984, Value 30
For Persons:
Address where add: 2151492060192, Value: Miguel, 23 Address where add: 2151492060200, Value: Elena, 24 Address where add: 2151492060208, Value: Ana, 34 Address where add: 2151492060216, Value: Ulises, 23 Address to return: 2151492060192, Value Miguel, 23 Address to return: 2151492060200, Value Elena, 24 Address to return: 2151492060208, Value Ana, 34 Address to return: 2151492060216, Value Ulises, 23
Why the results are not consistent when use Int32? I'm new in c# pointers.