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

Do you have any good resources on writing dlls to consume via .net like you’re talking about ?

How do you deal with the managed memory when using the gc from .net




> Do you have any good resources on writing dlls to consume via .net like you’re talking about?

For C APIs i.e. functions, structures and strings, the good resource is Microsoft documentation, the support is built-in, see “Consuming Unmanaged DLL Functions” section: https://docs.microsoft.com/en-us/dotnet/framework/interop/

For COM APIs i.e. sharing objects around see this library + demos: https://github.com/Const-me/ComLightInterop It’s only really needed on Linux because the desktop version of the framework has COM support already built-in, but it can be used for cross-platform things just fine, I tested that quite well i.e. not just with these simple demos.

> How do you deal with the managed memory when using the gc from .net

Most of the time, automatically.

When you calling C++ from C#, the runtime automatically pins arguments like strings or arrays. Pinning means until the C++ function returns, .NET GC won’t touch these things. This doesn’t normally make any copies: C++ will receive raw pointers/native references to the .NET objects.

Sometimes you do want to retain C# objects from C++ or vice versa i.e. keep them alive after the function/method returns. An idiomatic solution for these use cases is COM interop. IUnknown interface (a base interface for the rest of COM interfaces) allows to retain/release things across languages.


On Windows, just use C++/CLI or COM.

Contrary to urban myths, all major APIs introduced since Vista are mostly COM.

On other platforms, P/Invoke provides a very straightforward way to bind into C ABI.

You can manage native memory via "using" (since C# 8.0 you don't even need to implement IDisposable), or SafeHandles.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

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

Search: