Why do PinGCArrayAndGetDataAddress & AddressOf return different addresses ?

In the below code snipped addresses in the variables _TData and _PData are different, Dereferencing _PData gives the correct value where as _TData returns garbage value. Is the difference cuz of, in case of PinGCObjectAndGetAddress the struct is passed by value. If that’s the case how do you pin a struct value ?

var vector = new Vector3(1,10,1);

_TData = UnsafeUtility.PinGCObjectAndGetAddress(vector, out _gc);
_PData = UnsafeUtility.AddressOf(ref vector);

I am trying to avoid nested native containers. I have a struct with native array as a member. So to have a Native array of theses structs I though I can store the pointers to the structs in a native array and dereference them when required and for this pinning is essential.

Pretty sure you are on the money here. You are boxing the struct then pinning the object.

1 Like

Even if that’s happening (I don’t mind the address being different) why would dereferencing _TData return a Vector3 with garbage value. If the boxed object it pinned shouldn’t it also have the same values ?

The address of the box isn’t necessarily the address of the actual value in the box - you could be looking at the managed object header. If I were to guess, you need to offset the address by a couple of sizeof(IntPtr) s.

(Not that this will help you in any way - take a look at NativeReference if you haven’t already, it might be a better way to stash a struct and get a pointer to it)

1 Like