文章目录
- 前言
- 一、创建C/C++动态库
- 1.新建工程
- 2.添加模拟测试驱动
- 2.头文件声明
- 3.模块定义声明
- 4.编译生成库文件
- 二、创建C#库
- 1.新建工程
- 2.添加源码
- 3.编译生成库文件
- 三、应用测试
- 1.新建WinForm工程
- 2.引用库
- 3.应用测试
- 4.设置运行
- 5.测试
- 总结
前言
在项目开发中经常会遇到C/C++的动态链接库,而上位机采用C#的方式进行开发。对于某些应用不适用直接使用非托管的方式调用C/C++中的接口,本文就介绍在C#中采用中间层调用C++动态库,并将其封装成C#的库文件,将符合C#的库文件用于发布使用。
一、创建C/C++动态库
1.新建工程
2.添加模拟测试驱动
#include "stdafx.h"#include "board_driver.h"#define DEFAULT_HANDLE0x2000int board_open(unsigned int* handle){*handle = DEFAULT_HANDLE;return 0;}int board_close(unsigned int handle){return handle;}int board_calc(int a, int b){return a + b;}
2.头文件声明
#ifndef __BOARD_DRIVER_H#define __BOARD_DRIVER_Hint board_open(unsigned int* handle);int board_close(unsigned int handle);int board_calc(int a, int b);#endif
3.模块定义声明
模块声明需要导出的函数。
LIBRARY"board_driver"EXPORTSboard_open @1board_close @2board_calc @3
4.编译生成库文件
选择重新生成;
二、创建C#库
1.新建工程
在同一解决方案下新建C#库工程。
2.添加源码
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Runtime.InteropServices;namespace CBoardDriver{public class BoardDriver{[DllImport("board_driver.dll", EntryPoint = "board_open", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl)]public static extern int board_open(ref UInt32 handle);[DllImport("board_driver.dll", EntryPoint = "board_close", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl)]public static extern int board_close(UInt32 handle);[DllImport("board_driver.dll", EntryPoint = "board_calc", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl)]public static extern int board_calc(int a,int b);/// /// 重写接口/// /// /// public int BoardOpen(ref UInt32 handle){return board_open(ref handle);}/// /// 重写接口/// /// /// public int BoardClose(UInt32 handle){return board_close(handle);}/// /// 重写接口/// /// /// public int BoardCalc(int a,int b){return board_calc(a, b);}}}
3.编译生成库文件
三、应用测试
1.新建WinForm工程
2.引用库
3.应用测试
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;using CBoardDriver;namespace CBoardTest{public partial class Form1 : Form{/// /// /// BoardDriver boardDriver;/// /// /// UInt32 handle;public Form1(){InitializeComponent();//handle = 0;//实例boardDriver = new BoardDriver();}private void button1_Click(object sender, EventArgs e){ boardDriver.BoardOpen(ref handle);}private void button2_Click(object sender, EventArgs e){int status = 0;status = boardDriver.BoardClose(handle);}private void button3_Click(object sender, EventArgs e){int result = 0;result = boardDriver.BoardCalc(4, 5);}}}
4.设置运行
设置测试工程为启动项目;
将C/C++库拷贝到可执行程序路径;
5.测试
在Open中读取到在C/C++库中设置的默认值;
在Calc中实现两数相加;
总结
以上就是本次记录的内容,本文仅仅简单介绍了C#采用中间件调用C/C++库的实现流程;