WDUK
WDUK

Reputation: 1524

How to get the value from my pointer address in C#?

I am creating a pointer and storing this in a native hash map, but how do I convert this back to my struct when getting the value back?

I create it like this:

T* p = &myStruct;
hashMap.Add(myStruct, (int)p); //<MyStruct,int>

Now reading it back I am trying to do:

if(hashMap.TryGetValue(item, out int ptr)){

    T myStruct = *ptr; // don't know the right syntax here

    Debug.Log(myStruct.Equals(item)); // should be the same
}

I cannot use IntPtr because I cannot use Marshal.PtrToStructure. Unity's compiler does not allow it within its threads.

Upvotes: 3

Views: 486

Answers (2)

Chuck
Chuck

Reputation: 2102

I just wanted to add in here that I think you can use Marshal.PtrToStructure if you tick the "allow unsafe code" option in the compilation settings. Go to:

Edit > Project Settings > Player > Other Settings > Script Compilation > "Allow 'unsafe' Code"

enter image description here

Upvotes: 0

derHugo
derHugo

Reputation: 90669

You are close but the int ptr you get there is still an int address, not a pointer!

I think what you are looking for would be something like

 T myStruct = *((T*)ptr);

so first convert the address back to a pointer and then dereference it.

Paranthesis is redundant, just thought it is easier to understand this way. You can also just do

T myStruct = *(T*)ptr;

or in steps

if(hashMap.TryGetValue(item, out int addr))
{
    T* ptr = (T*)addr;
    T myStruct = *ptr;

    Debug.Log(myStruct.Equals(item));
}

Upvotes: 3

Related Questions