C语言:封装DLL并用C#调用
新建C++win32空项目//main.h 创建头文件#pragma once//#ifdef _MSC_VER && __cplusplus//#define SDK_APIextern "C" __declspec(dllexport)//#else//#define SDK_API extern "C"//#endif__declspec(dllexport) void ke
·
新建C++win32空项目
//main.h 创建头文件
#pragma once
//#ifdef _MSC_VER && __cplusplus
//#define SDK_API extern "C" __declspec(dllexport)
//#else
//#define SDK_API extern "C"
//#endif
__declspec(dllexport) void key();
//main.c 要封装的源文件
#include "main.h" //添加头文件
void key()
{
//主函数
}
修改项目属性:
输出目录:之后创建的C#项目位置
KeyAuthCSharpDemo\KeyAuthCSharpDemo\bin\Debug
新建C#项目-windows窗体应用
//Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace KeyAuthCSharpDemo
{
public partial class Form1 : Form
{
[DllImport("KeyAuthDll.dll", CallingConvention = CallingConvention.Cdecl)]
public extern static void key();
public Form1()
{
InitializeComponent();
key();
}
}
}
---------------------------------------------------------------------------------------------------------
//补充:调用dll函数时要传入浮点型参数
namespace Demo
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
[DllImport("keyStrokeRec.dll", CallingConvention = CallingConvention.Cdecl)]
public extern static int StopHook(ref float feature); // ref 传入传出
//某个事件调用stophook函数
private void tb_password_Leave(object sender, EventArgs e)
{
float[] feature = new float[4]; //声明浮点型数组,长度为4
StopHook(ref feature[0]); //将数组传入函数
}
修改项目属性:
生成DLL项目解决方案
生成C#项目解决方案
感谢我伟大的同事手把手教我呜呜呜!
//DLL中有函数
extern "C" __declspec(dllexport) BOOL StopHook(float* feature);
//C#引用时应写为
[DllImport("keyStrokeRec.dll", CallingConvention = CallingConvention.Cdecl)]
public extern static int StopHook(ref float feature); //ref
//在C#中调用
float[] feature = new float[4];
StopHook(ref feature[0]);
//feature为空数组,作为参数传入
//在dll中的stophook函数中改变后C#中的该参数也改变了
//因为C不能直接返回数组
C#中有多个窗体需要调用Dll时,无需重复声明
//新建一个C#空类定义 DllFun.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace KDemo //注意这里
{
//dll接口类,不用重复声明
class DllFun
{
[DllImport("keyStrokeRec.dll", CallingConvention = CallingConvention.Cdecl)]
public extern static int StartHook();
}
}
//在调用Dll的窗体中加入
using KDemo;
//调用函数时应写
DllFun.StartHook();
更多推荐


所有评论(0)