我需要做什么才能在 C# 中使用 C++ DLL?

问题描述 投票:0回答:1

所以,我正在考虑使用 C# 启动器构建一个 C++ 应用程序,所以我决定将 C++ 程序放在一个 dll 中。
我读了Microsoft的文档关于制作一个dll,它告诉我我需要把函数和变量声明放在头文件中。
在我的情况下我需要做同样的事情吗 或者我只需要做:

[DLLImport("cppprogram.dll")]

注意:我不想使用 C++/CLI,它必须在 DLL 中

c# c++ dll
1个回答
-1
投票

您需要创建一个包装器或互操作层,将 DLL 中的函数公开为一组可以从 C# 调用的托管代码函数。

创建互操作层有两种通用方法:

  1. 使用P/Invoke:P/Invoke(Platform Invocation Services)是一种在.NET中从托管代码(如C#代码)调用非托管代码(如C++代码)的技术。 P/Invoke 允许您在 C# 代码中声明非托管函数,并像调用普通托管代码函数一样调用它们。要使用 P/Invoke,您需要创建一个 C# 类,其中包含与您要调用的 C++ 函数匹配的方法签名,并使用 DllImport 属性修饰它们以指定 C++ DLL 的名称和位置。
using System.Runtime.InteropServices;

class MyCppWrapper
{
    // Declare the unmanaged function in the C++ DLL
    [DllImport("MyCppDLL.dll")]
    public static extern int MyCppFunction(int arg1, int arg2);
}

// Call the C++ function from C#
int result = MyCppWrapper.MyCppFunction(42, 69);
  1. 使用C++/CLI:C++/CLI(Common Language Infrastructure)是一种允许您编写可直接调用非托管代码并与非托管代码互操作的托管代码的语言。使用 C++/CLI,您可以创建一个托管包装类,将 C++ DLL 中的函数公开为可从 C# 调用的托管函数。要使用 C++/CLI,您需要在 Visual Studio 中创建一个新的 C++/CLI 项目,添加对 C++ DLL 的引用,并创建一个调用非托管函数的托管包装类。
// This is the unmanaged function in the C++ DLL
int MyCppFunction(int arg1, int arg2)
{
    return arg1 + arg2;
}

// This is the managed wrapper class in the C++/CLI project
public ref class MyCppWrapper
{
public:
    static int MyManagedFunction(int arg1, int arg2)
    {
        return MyCppFunction(arg1, arg2);
    }
};

// Call the C++ function from C#
int result = MyCppWrapper::MyManagedFunction(42, 69);
© www.soinside.com 2019 - 2024. All rights reserved.