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);
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章