VC中制作DLL 动态链接库 函数回调MFC dll

新建win32的dll或者MFC的DLL

win32的DLL可手动添加一个.h文件,并且和对应的cpp文件对应,如下demo

// DemoDll2.cpp : 定义 DLL 应用程序的导出函数。
//

#include "stdafx.h"
#include "DemoDll2.h"

#include "stdio.h"  

#define MYLIBAPI  extern "C" __declspec( dllexport )    

void sayHello(char * name){  
	printf("C Code Start...\n");  
	printf("Hello! Mr %s.\n",name);  
	printf("C Code End.\n");  
}  

// DemoDll2.h : 定义 DLL 应用程序的导出函数。

#ifdef MYLIBAPI
#else
#define  MYLIBAPI  extern "C" __declspec(dllimport)    
#endif


MYLIBAPI void sayHello(char * name);

============================================

基于MFC的DLL函数回调实现

// CallBackDll.h : CallBackDll DLL 的主头文件
//

#pragma once

#ifndef __AFXWIN_H__
	#error "在包含此文件之前包含“stdafx.h”以生成 PCH 文件"
#endif

#include "resource.h"		// 主符号

#ifdef MYLIBAPI  
#else  
#define  MYLIBAPI  extern "C" __declspec(dllimport)      
#endif  


typedef int(*MyCallBack)(long user,int a,int b);

// CCallBackDllApp
// 有关此类实现的信息,请参阅 CallBackDll.cpp
//

class CCallBackDllApp : public CWinApp
{
public:
	CCallBackDllApp();

// 重写
public:
	virtual BOOL InitInstance();

	DECLARE_MESSAGE_MAP()
};

MYLIBAPI int dllAdd(int a,int b);

//long user调用dll的窗口的指针
MYLIBAPI void setCallFunction(long user,int (*Add)(long , int , int ));

// CallBackDll.cpp : 定义 DLL 的初始化例程。
//

#include "stdafx.h"
#include "CallBackDll.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

#define MYLIBAPI  extern "C" __declspec( dllexport )  

// CCallBackDllApp

BEGIN_MESSAGE_MAP(CCallBackDllApp, CWinApp)
END_MESSAGE_MAP()


// CCallBackDllApp 构造

CCallBackDllApp::CCallBackDllApp()
{
	// TODO: 在此处添加构造代码,
	// 将所有重要的初始化放置在 InitInstance 中
}


// 唯一的一个 CCallBackDllApp 对象

CCallBackDllApp theApp;


// CCallBackDllApp 初始化

BOOL CCallBackDllApp::InitInstance()
{
	CWinApp::InitInstance();

	return TRUE;
}

MyCallBack myAdd;
long dUser;
void setCallFunction(long user,int (*Add)(long, int , int ))
{
	myAdd=Add;
	dUser=user;
}

int dllAdd(int a,int b)
{
	int x=myAdd(dUser,a,b);
	return x;
}

//测试dll的MFC程序

int myAdd(long user,int a,int b)
{
	CDllTestDlg* dlg=(CDllTestDlg*)user;//将user强制转成该类的一个指针
	CString cs;
	cs.Format("a=%d ,b=%d",a,b);
	dlg->MessageBox("回调成功啦!\r\n"+cs);
        dlg->MessageBox(dlg->temp);
        return a+b;
}
void CDllTestDlg::OnBnClickedButton1()
{
	// TODO: 在此添加控件通知处理程序代码
        temp="这是this中的测试字符串";
        setCallFunction((long)this,myAdd);//此处将this指针传递到回调函数中
	int x=dllAdd(3,4);

	CString cs;
	cs.Format("结果为:%d",x);
	MessageBox(cs);
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值