Search code examples
winapinative-codewin-universal-app

How do I write a Windows 10 universal class library that references native code?


I have a C# class library that references and wraps Win32 native methods. But I can't seem to port this code over to a newer "universal" C# class library. What do I need to do in order to properly marshal these native methods?


Solution

  • Windows 10 Universal Applications run under the Windows Runtime API, a new "native" API for Windows. Applications using this API run in a sandbox which limits their access to devices and operating system services. While Win32 APIs can be accessed like normal, for example using P/Invoke in the case of C# code, the sandbox only permits the use of certain API functions:

    Windows Runtime apps can use a subset of the Win32 and COM APIs. This subset of APIs was chosen to support key scenarios for Windows Runtime apps that were not already covered by the Windows Runtime, HTML/CSS, or other supported languages or standards. The Windows App Certification Kit ensures that your app uses only this subset of the Win32 and COM API. In a native app, you can call these APIs directly. In a managed app, you can call them via a Windows Runtime Component, or via P/Invoke.

    ...

    The documentation for each programming element in the API indicates whether it can be used in a Windows Runtime app. See the "Applies to" line at the top of the page.

    So for example FormatMessage works with Windows Runtime, but GetNamedPipeInfo doesn't.

    If the Win32 API you want to use isn't one of the ones supported by Windows Runtime, I believe your only option is to have your class library target traditional desktop apps.