Calling LoadLibrary using pinvoke from UWP C# application
Asked Answered
S

1

7

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!

Salomon answered 10/8, 2017 at 18:7 Comment(3)
Indeed, there is no entry point named LoadLibrary in kernel32.dll. There are two others: LoadLibraryA for ANSI strings and LoadLibraryW for Unicode strings. You want the latter. No guarantee it works then, though. From what I gather you're supposed to use LoadPackagedLibrary on UWP (but I'm not a UWP developer).Vigil
LoadLibraryW() is verboten in a UWP app. You cannot get your app certified and can't sell and deploy through the store.Katherinkatherina
You sure about that? I was able to get LoadLibraryW loaded through the [DllImport("API-MS-WIN-CORE-LIBRARYLOADER-L2-1-0.DLL", SetLastError = true)] import.Salomon
B
5

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);
Bovine answered 11/8, 2017 at 4:1 Comment(1)
Sorry, I made a typo. Fixed now.Bovine

© 2022 - 2024 — McMap. All rights reserved.