Hacker News new | past | comments | ask | show | jobs | submit login

Pinning is always done for heap-allocated GC memory, yes. Otherwise fixed statement does nothing for pointers/byrefs that originate from stack and it should be also a no-op for e.g. NativeMemory.Alloc-returned pointers.

On the other hand, GCHandles[0] are rare and only ever needed when you have complex object lifetime where, for example, the object reference needs to be passed back from unmanaged and object needs to survive in the meantime. The unmanaged code cannot interact with an object itself because it is not representable and would have arbitrary layout.

Today, there is support for multiple calling conventions and ways to interact with FFI. [UnmanagedCallersOnly] exports with NativeAOT-compiled libraries are C exports in the same way they are for the dynamic (or static) libraries compiled with GCC. Various flavours of function pointers have existed for a long time, yes. The most recent one allows to cast pointers directly to the desired unmanaged function signature within unsafe code, or create one given mentioned UnmanagedCallersOnly annotation on a C# method.

[0] https://learn.microsoft.com/en-us/dotnet/api/system.runtime.... note specific use case, it's not the bread and butter regular marshaling and pinning are




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: