Reference native c++ dll in UWP project

2019-08-20 07:30发布

问题:

I have a c++ dll that I want to utilize in the UWP project that I am working on. I need some assistant on how to achieve that.

回答1:

C++ doesn't have a concept of "referencing DLLs". All you need to do to use them is to make sure they're copied next to your executable when you build your app. If you're using Visual Studio C# project (.csproj), add it to it as "Content" type:

<ItemGroup Condition="'$(Platform)' == 'x86'">
  <Content Include="$(ProjectDir)MyDLL\x86\MyDLL.dll">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  </Content>
</ItemGroup>
<ItemGroup Condition="'$(Platform)' == 'x64'">
  <Content Include="$(ProjectDir)MyDLL\x64\MyDLL.dll">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  </Content>
</ItemGroup>

Once you have this setup, it's just a matter of P/Invoking into it, for instance:

[DllImport("MyDLL.dll")]
void DoStuff();


回答2:

Universal Windows Apps run in a restricted runtime environment, so you can't just use any native DLL the way you would in a classic Windows desktop application. If you have source code for a DLL, you can port the code so that it runs on the UWP. You start by changing a few project settings and project file metadata to identify the project as a UWP project. You need to compile the library code using the /ZW option, which enables C++/CX. Certain API calls are not allowed in UWP apps due to stricter controls associated with that environment. See Win32 and COM APIs for UWP apps.

If your native DLL exposes functions using __declspec(dllexport), then you could follow the procedure on Using a Win32 DLL in a UWP App.