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