WPF与C++动态库交互技术详解
一、基本交互方式概述
WPF应用程序与C++动态库交互主要有以下几种方式:
- P/Invoke调用(平台调用)
- COM互操作
- C++/CLI桥接层
- 内存映射文件
- 命名管道/Socket通信
本文将重点介绍最常用的P/Invoke和C++/CLI两种方式。
二、P/Invoke调用C++动态库
1. C++动态库创建
示例C++代码 (MyLibrary.cpp):
#include <string>
#include <vector>
extern "C" {
// 简单函数
__declspec(dllexport) int AddNumbers(int a, int b) {
return a + b;
}
// 返回字符串
__declspec(dllexport) const char* GetMessage() {
return "Hello from C++";
}
// 结构体处理
struct Point {
double X;
double Y;
};
__declspec(dllexport) Point GetPoint(double x, double y) {
Point p = {x, y};
return p;
}
}
编译为DLL:
cl /EHsc /LD MyLibrary.cpp /link /OUT:MyLibrary.dll
2. WPF中调用C++ DLL
P/Invoke声明 (NativeMethods.cs):
using System;
using System.Runtime.InteropServices;
public static class NativeMethods
{
// 简单函数调用
[DllImport("MyLibrary.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int AddNumbers(int a, int b);
// 返回字符串
[DllImport("MyLibrary.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr GetMessage();
// 结构体处理
[StructLayout(LayoutKind.Sequential)]
public struct Point
{
public double X;
public double Y;
}
[DllImport("MyLibrary.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern Point GetPoint(double x, double y);
// 辅助方法:释放字符串内存
[DllImport("MyLibrary.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void FreeString(IntPtr str);
}
注意:如果C++函数返回的是动态分配的字符串,需要在C++端提供释放函数。
改进的C++代码 (添加FreeString):
extern "C" {
__declspec