要在C++中調用C#的DLL文件,您可以使用C++/CLI(C++ Common Language Infrastructure)作為橋梁。C++/CLI允許您在C++代碼中直接調用.NET Framework的組件。以下是調用C# DLL的步驟:
MyCSharpLibrary
的DLL,其中包含一個名為MyClass
的類和一個名為MyMethod
的方法。// MyCSharpLibrary.cs
using System;
namespace MyCSharpLibrary
{
public class MyClass
{
public string MyMethod(string input)
{
return input.ToUpper();
}
}
}
編譯C# DLL并將其添加到C++項目中。在Visual Studio中,右鍵單擊C++項目,選擇“添加引用”,然后瀏覽到C# DLL并添加它。
創建一個C++/CLI包裝器類來調用C# DLL中的方法。在C++項目中創建一個新的類,例如MyCppWrapper
,并添加以下代碼:
// MyCppWrapper.h
#pragma once
#include <msclr/auto_gcroot.h>
#include "MyCSharpLibrary.h"
namespace MyCppWrapper
{
public ref class MyWrapper
{
public:
std::string CallMyMethod(std::string input)
{
msclr::auto_gcroot<MyCSharpLibrary::MyClass^> myClass = gcnew MyCSharpLibrary::MyClass();
return myClass->MyMethod(input);
}
};
}
MyCppWrapper
類調用C# DLL中的方法。例如,在main.cpp
中添加以下代碼:// main.cpp
#include <iostream>
#include "MyCppWrapper.h"
int main(array<System::String ^> ^args)
{
MyCppWrapper::MyWrapper^ myWrapper = gcnew MyCppWrapper::MyWrapper();
std::string input = "Hello, World!";
std::string output = myWrapper->CallMyMethod(input);
std::cout << "Input: " << input << std::endl;
std::cout << "Output: " << output << std::endl;
return 0;
}
注意:在C++/CLI中,我們使用msclr::auto_gcroot
來管理C#對象的內存。這是因為C++/CLI是一種混合了原生C++和.NET Framework的編程語言,它需要使用托管類型和非托管類型之間的互操作性。