Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling LoadLibrary using pinvoke from UWP C# application

Tags:

c#

pinvoke

uwp

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!

like image 399
TheJeff Avatar asked Aug 10 '17 18:08

TheJeff


1 Answers

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);
like image 139
Sunius Avatar answered Oct 15 '22 08:10

Sunius