要在WPF中調用C++庫,可以使用以下方法:
創建一個C++/CLI封裝器:
在WPF項目中引用封裝器:
using
關鍵字導入封裝器的命名空間。下面是一個簡單的示例:
C++/CLI封裝器代碼(MyWrapper.h):
#pragma once
#include "myCppLibrary.h"
using namespace System;
namespace MyWrapper {
public ref class MyWrapperClass
{
private:
MyCppLibrary::MyCppClass* myCppObj;
public:
MyWrapperClass();
~MyWrapperClass();
int Add(int a, int b);
};
}
C++/CLI封裝器代碼(MyWrapper.cpp):
#include "MyWrapper.h"
MyWrapper::MyWrapperClass::MyWrapperClass()
{
myCppObj = new MyCppLibrary::MyCppClass();
}
MyWrapper::MyWrapperClass::~MyWrapperClass()
{
delete myCppObj;
}
int MyWrapper::MyWrapperClass::Add(int a, int b)
{
return myCppObj->Add(a, b);
}
WPF代碼(MainWindow.xaml.cs):
using System.Windows;
using MyWrapper;
namespace WpfApp
{
public partial class MainWindow : Window
{
MyWrapperClass myWrapperObj;
public MainWindow()
{
InitializeComponent();
myWrapperObj = new MyWrapperClass();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
int result = myWrapperObj.Add(5, 3);
MessageBox.Show(result.ToString());
}
}
}
請注意,上述示例假定已經存在一個名為myCppLibrary
的C++庫,并且已經正確配置了相關的項目引用和包含路徑。