Example #1
0
        private IntPtr RegisterPlatformSpecific(string absoluteFilePath,
                                                out NativeLibrary.SymbolLookupDelegate symbolLookup)
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                var handle = Posix.dlopen(absoluteFilePath, Posix.RTLD_LAZY | Posix.RTLD_GLOBAL);

                if (handle == IntPtr.Zero)
                {
                    throw new NativeLoaderException(
                              $"Failed to load '{absoluteFilePath}'. dlerror: {Marshal.PtrToStringAnsi(Posix.dlerror())}");
                }

                symbolLookup = Posix.dlsym;
                return(handle);
            }

            if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                var handle = Posix.dlopen(absoluteFilePath, Posix.RTLD_LAZY | Posix.RTLD_GLOBAL);

                if (handle == IntPtr.Zero)
                {
                    throw new NativeLoaderException(
                              $"Failed to load '{absoluteFilePath}'. dlerror: {Marshal.PtrToStringAnsi(Posix.dlerror())}");
                }

                symbolLookup = Posix.dlsym;
                return(handle);
            }

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                var dllDirectory = Path.GetDirectoryName(absoluteFilePath);
                var fileName     = Path.GetFileName(absoluteFilePath);

                Windows.SetDllDirectory(dllDirectory);
                var handle = Windows.LoadLibrary(fileName);

                if (handle == IntPtr.Zero)
                {
                    throw new NativeLoaderException(
                              $"Failed to load '{absoluteFilePath}'. LoadLibrary: {Windows.GetLastError():X8}");
                }

                symbolLookup = Windows.GetProcAddress;
                return(handle);
            }

            throw new NativeLoaderException($"Platform '{Environment.OSVersion.Platform}' is not supported.");
        }