Search code examples
c#uwppinvoke

Calling LoadLibrary using pinvoke from UWP C# application


I'm trying to call methods from an unmanaged dll from a C# UWP application. I do this, but pinvoking "LoadLibrary()" on the unmanaged dll so that I can use it.

This all works fine in Debug mode, however in Release mode, I get a curious error:

Message: Class Initialization method Tests.UnitTests.InitializeClient threw exception. System.TypeLoadException: System.TypeLoadException: Unresolved P/Invoke method 'LoadLibrary!kernel32' in assembly 'Client, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because it is not available in UWP applications. Please either use an another API , or use [DllImport(ExactSpelling=true) to indicate that you understand the implications of using non-UWP application APIs..

Here is my method to pinvoke Load Library:

    [DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)]
    public static extern IntPtr LoadLibrary(string librayName);

Unfortunately, if I add the "ExactSpelling = true" as below:

    [DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
    public static extern IntPtr LoadLibrary(string librayName);

Then calling it throws an exception:

System.EntryPointNotFoundException: 'Unable to find an entry point named 'LoadLibrary' in DLL 'kernel32'.'

Any help is much appreciated!


Solution

  • Use LoadPackagedLibrary instead:

    [DllImport("API-MS-WIN-CORE-LIBRARYLOADER-L2-1-0.DLL", SetLastError = true)]
    public static extern IntPtr LoadPackagedLibrary([MarshalAs(UnmanagedType.LPWStr)]string libraryName, int reserved = 0);