C#--使用CMake构建C++程序调用示例
1.C++代码
// example.cpp#include <iostream>extern "C" {__declspec(dllexport) void PrintMessage() {std::cout << "Hello from C++!" << std::endl;}
}
2.CMakeLists.txt文件,用于使用CMake构建C++库:
# CMakeLists.txtcmake_minimum_required(VERSION 3.0)project(Example)add_library(example SHARED example.cpp)
3.C#代码--通过PInvoke调用C++函数:
// Program.csusing System;
using System.Runtime.InteropServices;class Program
{[DllImport("example", CallingConvention = CallingConvention.Cdecl)]public static extern void PrintMessage();static void Main(){PrintMessage(); // 调用C++函数}
}
4.小结:
上述示例中,定义了一个简单的C++函数PrintMessage,然后使用CMake构建了一个名为example的动态链接库。在C#代码中,我们使用DllImport特性声明了PrintMessage函数,并在Main函数中调用这个函数。通过这种方式即实现了在C#中调用C++函数的功能。
同时需要注意非托管函数的参数传递、内存管理等问题
5.(Cmake)补充:
- 组织项目结构和文件,告诉编译器哪些文件需要编译,如何相互关联。
- 确定编译参数,比如优化级别、目标平台等。
- 处理不同操作系统下的构建过程,让你的项目能够在不同的电脑上顺利构建。
即CMake协助管理整个项目的构建过程,更方便地把代码变成可执行的软件。