Search Unity

Question Why do PinGCArrayAndGetDataAddress & AddressOf return different addresses ?

Discussion in 'Entity Component System' started by X-BLaZeKiLL-X, Sep 5, 2021.

  1. X-BLaZeKiLL-X

    X-BLaZeKiLL-X

    Joined:
    Apr 9, 2013
    Posts:
    6
    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 ?

    Code (CSharp):
    1.            
    2. var vector = new Vector3(1,10,1);
    3.  
    4. _TData = UnsafeUtility.PinGCObjectAndGetAddress(vector, out _gc);
    5. _PData = UnsafeUtility.AddressOf(ref vector);
    6.  
    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.
     
  2. tertle

    tertle

    Joined:
    Jan 25, 2011
    Posts:
    3,759
    Pretty sure you are on the money here. You are boxing the struct then pinning the object.
     
    apkdev likes this.
  3. X-BLaZeKiLL-X

    X-BLaZeKiLL-X

    Joined:
    Apr 9, 2013
    Posts:
    6
    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 ?
     
  4. apkdev

    apkdev

    Joined:
    Dec 12, 2015
    Posts:
    283
    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<T> if you haven't already, it might be a better way to stash a struct and get a pointer to it)
     
    OndrejP likes this.