News for hackers. Stuff that matters.
Re:C# 9 top-level programs and target-typed expressions by binarynate on Tuesday March 30, 2021 @10:16PM (#26642824)
Yes, native interop works the same across all platforms (Linux, macOS, Windows, Android, iOS). You can just place a dynamic library with C linkage (.so, .dylib, or .dll file) into your app's folder, and then you can call the native functions as external functions in C#. For example, if your library exports the following C function:

    void printMessage(char *message) {
        printf("Message from C#: %s", message)
    }
You can call it from C# like this:

    MyLibrary.printMessage("Hello from C#!");

    public static class MyLibrary {
        [DllImport("MyLibraryName")]
        public static extern void printMessage(string message);
    }
C# takes care of marshalling data types, and an instance of a native object can be passed as an IntPtr. I'm currently developing web services for a new WebRTC-related product using .NET 5 on Ubuntu, and it's working well. One of the services utilizes a native C++ library and another utilizes a native Go-based library using the same approach. Java and Go are both good options, too.
Re:C# 9 top-level programs and target-typed expressions by zwieback on Wednesday March 31, 2021 @12:24AM (#26643502)
Thanks, I'll give it a try. I've done a lot of interop in Windows so it'll be good to leverage to Linux.
Re:C# 9 top-level programs and target-typed expressions by merb on Wednesday March 31, 2021 @07:21AM (#26645839)
it's a little bit harder when your linux library is not inside LD_LIBRARY_PATH or the windows one is not inside a path. but there are tricks to override the loading behavior, it's just a little bit tricky since you need a loading context, which can load other c# dll's without having a reference to them.

it's basically like that: AssemblyLoadContext loads the managed assembly (like YourPackage.NativeApi which contains the DllImport) and the AssemblyLoadContext that loads via LoadUnmanagedDll all paths to the DllImports. you also need a Shared Library for the calling package and the dll import package so that you can do (Type)Activator.CreateInstance(LoadContext.LoadFromAssemblyName(YourDllImportAssemblyName))