如何在C#编写的UWP项目中引入原生C++ DLL?
Hey there! I’ve walked many developers through integrating native C++ DLLs with C# UWP projects, so let me break this down into clear, actionable steps for you—whether you want to use direct DLL imports or the more seamless WinRT component approach.
Option 1: Directly Import a Native C++ DLL into C# UWP
This method uses DllImport to call native functions directly, which works well for simple, straightforward logic.
Step 1: Create a C++ UWP DLL Project
- Open Visual Studio, click Create a new project.
- Search for Dynamic-Link Library (UWP), select the template, then click Next.
- Name your project (e.g.,
NativeCppDll), choose a save location, and click Create.
Step 2: Write Exportable Native Functions
- Create a new header file (e.g.,
NativeFunctions.h) and source file (e.g.,NativeFunctions.cpp) in the C++ project, or modify existing files likedllmain.cpp. - In the header, define your exported functions using
extern "C"(to avoid C++ name mangling) and__declspec(dllexport):
// NativeFunctions.h #pragma once #ifdef NATIVECPPDLL_EXPORTS #define NATIVECPPDLL_API __declspec(dllexport) #else #define NATIVECPPDLL_API __declspec(dllimport) #endif extern "C" { // Example: Return sum of two integers NATIVECPPDLL_API int Add(int a, int b); // Example: Print a message to the debug console NATIVECPPDLL_API void PrintMessage(const wchar_t* message); }
- Implement the functions in the source file:
// NativeFunctions.cpp #include "pch.h" #include "NativeFunctions.h" #include <windows.h> int Add(int a, int b) { return a + b; } void PrintMessage(const wchar_t* message) { OutputDebugStringW(message); }
- Build the C++ project to generate the
NativeCppDll.dlland.libfiles (found in theDebug/Releasefolder matching your target platform).
Step 3: Integrate the DLL into Your C# UWP Project
- Open your C# UWP project, right-click the project > Add > Existing Item.
- Navigate to the generated
NativeCppDll.dll, add it to your project (I recommend putting it in a dedicated folder likeNativeDlls). - Select the DLL in the Solution Explorer, go to the Properties window:
- Set Copy to Output Directory to Copy always
- Set Build Action to Content
- In your C# code, use
[DllImport]to import the native functions:
using System.Runtime.InteropServices; using System.Diagnostics; public static class NativeDllWrapper { // Import the Add function (match the DLL name and calling convention) [DllImport("NativeCppDll.dll", CallingConvention = CallingConvention.Cdecl)] public static extern int Add(int a, int b); // Import the PrintMessage function (use Unicode for wide strings) [DllImport("NativeCppDll.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern void PrintMessage(string message); }
- Now call the functions in your C# code like any other method:
int sum = NativeDllWrapper.Add(4, 6); Debug.WriteLine($"C++ Add result: {sum}"); NativeDllWrapper.PrintMessage("Hello from C# calling native C++!");
Option 2: Use a Windows Runtime Component (C++) (Recommended)
This approach wraps your native C++ code in a WinRT component, making it accessible to C# like a regular .NET library—no DllImport needed, and it’s type-safe.
Step 1: Create a Windows Runtime Component (C++) Project
- Open Visual Studio, click Create a new project.
- Search for Windows Runtime Component (C++), select the template, click Next.
- Name it (e.g.,
NativeCppWinRTComponent), choose a save location, click Create.
Step 2: Wrap Native Code in a WinRT Class
- Open the auto-generated
.hand.cppfiles (or create new ones), then define a public sealed class:
// NativeOperations.h #pragma once namespace NativeCppWinRTComponent { public ref class NativeOperations sealed { public: int Add(int a, int b); void PrintMessage(Platform::String^ message); }; }
- Implement the class methods in the
.cppfile:
// NativeOperations.cpp #include "pch.h" #include "NativeOperations.h" #include <windows.h> using namespace NativeCppWinRTComponent; using namespace Platform; int NativeOperations::Add(int a, int b) { return a + b; } void NativeOperations::PrintMessage(String^ message) { OutputDebugStringW(message->Data()); }
- Build the WinRT component project.
Step 3: Reference and Use the Component in C# UWP
- In your C# UWP project, right-click References > Add Reference.
- Go to the Projects tab, select your
NativeCppWinRTComponentproject, click OK. - Now you can instantiate the WinRT class and call its methods directly:
using NativeCppWinRTComponent; using System.Diagnostics; // ... var nativeOps = new NativeOperations(); int sum = nativeOps.Add(10, 20); Debug.WriteLine($"WinRT Component Add result: {sum}"); nativeOps.PrintMessage("Hello from WinRT-wrapped C++ code!");
Key Things to Keep in Mind
- Platform Consistency: Make sure your C++ project and C# UWP target the same platform (x64, ARM64, etc.)—mismatches will cause runtime errors.
- UWP Permissions: If your native code accesses system resources (like files, network), ensure your C# UWP project’s
Package.appxmanifestdeclares the required capabilities. - String Handling: For wide strings (
wchar_t*in C++), useCharSet.UnicodeinDllImportorPlatform::String^in WinRT to avoid encoding issues. - Calling Conventions: Match the calling convention between C++ and C#—most native C++ code uses
cdecl, which you need to specify inDllImport.
内容的提问来源于stack exchange,提问作者mark
相关产品推荐
相关产品推荐

