dotnet / standard

This repo is building the .NET Standard
3.07k stars 428 forks source link

Any plans to support NativeLibrary in dotnet standard? #1764

Closed ryandanthony closed 2 years ago

ryandanthony commented 4 years ago

Are there any plans, or is it even possible, to support NativeLibrary in dotnet standard?

https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.nativelibrary?view=netcore-3.1

I have a dotnet standard 2.1 library that needs to load a c++ library, but we want to support multiple versions of the library (linux and windows).

Example usage:

static class NativeMethods
{
    private const string LibraryName = "something";
    static NativeMethods()
    {
        NativeLibrary.SetDllImportResolver(typeof(NativeMethods).Assembly, ImportResolver);
    }
    private static IntPtr ImportResolver(string libraryName, Assembly assembly, DllImportSearchPath? searchPath)
    {
        IntPtr libHandle = IntPtr.Zero;
        if (libraryName == NativeMethods.LibraryName)
        {
            string library;
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                library = "libsomething_c.so";  
            } 
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                library = "libsomething_c.dylib";
            }
            else
            {
                library = "libsomething_c.dll";
            }
            var libraryLoaded = NativeLibrary.TryLoad(library, assembly, DllImportSearchPath.AssemblyDirectory, out libHandle);
            if (!libraryLoaded)
            {
                throw new Exception($"Unable to Load Library: {library}");
            }
        }
        return libHandle;
    }

Alternatively, is there another way to load a cross platform C++ code in a dotnet standard?

gfoidl commented 4 years ago

is there another way to load a cross platform C++ code in a dotnet standard?

Does DllImport not suffice? The lib prefix and the file-extension is handled by the runtime depending on the OS (similar as you do manually in the code above).

NativeLibrary is really handy when -- especially on POSIX systems -- several versions of the library are available and need to be probed, i.e. can't be given as constant in DllImport.

terrajobst commented 2 years ago

Closing as not planned, as .NET Standard is considered complete.