Search code examples
c#pointersref

Is there any way to convert IntPtr / void* to ref SomeStruct in C#?


Subj. The use case is: let's assume I have an unmanaged buffer that stores N instances of SomeStruct. So having an address in this buffer, is there any way to convert this address to ref SomeStruct -- e.g. to be able to update these structs directly?

P.S. I am aware of upcoming Span<T> type. I am curious if there is any way to do something similar in C# right now.


Solution

  • Ok, found the answer: System.Runtime.CompilerServices.Unsafe.AsRef<T> solves the problem. More on this: http://adamsitnik.com/ref-returns-and-ref-locals/