所以,我正在考虑使用 C# 启动器构建一个 C++ 应用程序,所以我决定将 C++ 程序放在一个 dll 中。
我读了Microsoft的文档关于制作一个dll,它告诉我我需要把函数和变量声明放在头文件中。
在我的情况下我需要做同样的事情吗
或者我只需要做:
[DLLImport("cppprogram.dll")]
?您需要创建一个包装器或互操作层,将 DLL 中的函数公开为一组可以从 C# 调用的托管代码函数。
创建互操作层有两种通用方法:
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);
// 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);