要在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++库,并且已经正确配置了相关的项目引用和包含路径。