以下是一个简单的示例,演示如何在 C# 中调用 C++ DLL:

C++ DLL 代码:

// MyCppLibrary.cpp

#include "stdafx.h"

extern "C" __declspec(dllexport) int Add(int a, int b)
{
    return a + b;
}

C# 代码:

// Program.cs

using System;
using System.Runtime.InteropServices;

class Program
{
    [DllImport('MyCppLibrary.dll', CallingConvention = CallingConvention.Cdecl)]
    public static extern int Add(int a, int b);

    static void Main(string[] args)
    {
        int result = Add(2, 3);
        Console.WriteLine(result);
    }
}

在这个例子中,我们定义了一个简单的 C++ 函数 Add,它接受两个整数作为参数,并返回它们的和。我们使用 __declspec(dllexport) 来将函数导出为 DLL 函数。

在 C# 中,我们使用 DllImport 属性来引用 C++ DLL 中的函数。在这个例子中,我们使用 CallingConvention = CallingConvention.Cdecl 来指定调用约定为 Cdecl。

最后,在 Main 方法中,我们调用 Add 函数,并将结果打印到控制台上。

C# 调用 C++ DLL 完整示例 | 如何在 C# 中使用 C++ 库

原文地址: https://www.cveoy.top/t/topic/jkhX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录