WPF与C++ 动态库交互

WPF与C++动态库交互技术详解

一、基本交互方式概述

WPF应用程序与C++动态库交互主要有以下几种方式:

  1. ​P/Invoke调用​​(平台调用)
  2. ​COM互操作​
  3. ​C++/CLI桥接层​
  4. ​内存映射文件​
  5. ​命名管道/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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

code_shenbing

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值