You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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 like dllmain.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.dll and .lib files (found in the Debug/Release folder 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 like NativeDlls).
  • 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++!");

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 .h and .cpp files (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 .cpp file:
// 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 NativeCppWinRTComponent project, 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.appxmanifest declares the required capabilities.
  • String Handling: For wide strings (wchar_t* in C++), use CharSet.Unicode in DllImport or Platform::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 in DllImport.

内容的提问来源于stack exchange,提问作者mark

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:28:03