DLL+ ActiveX控件+WEB页面调用例子
2024-05-06 14:27:49
供稿:网友
一、 概述
因项目需要,开始学习并研究VC、DLL及ActiveX控件,网上资料找了很多,但没一个可用的或者说没一个例子可理解并运行的。没办法,自己研究吧。功夫不负有心人,终有小成了,呵呵,现在把自己学习总结了一下,献给需要的人。
DLL(动态链接库): 分WIN32 DLL和MFC DLL
ActiveX:分ATL控件和MFC控件两类(也是一个DLL)
WEB:JAVASCRIPT 调用-> ActiveX调用-> DLL 完成加法运算并返回值,在页面上显示。
二、开发(VS2008)
1、DLL 库编写:
文件-》新建-》WIN32控制台->填写项目名称-》选择DLL-》空项目-》完成。
(1)在解决方案面板中,加入一个头文件testdll.h,内容:
代码如下:
#ifndef _DLLTUT_DLL_H_
#define _DLLTUT_DLL_H_
#if defined DLL_EXPORT
#define DECLDIR __declspec(dllexport)
#else
#define DECLDIR __declspec(dllimport)
#endif
//extern "C"告诉编译器该部分可以在C/C++中使用。
extern "C"
{
DECLDIR int Add( int a, int b );
DECLDIR void Function( void );
}
#endif
(2)在解决方案面板中,加入一个实现文件testdll.cpp,内容:
代码如下:
#include <iostream>
#define DLL_EXPORT
#include "testdll.h"
extern "C"
{
// 这里主要用到 ADD 方法。
DECLDIR int Add( int a, int b )
{
return( a + b );
}
DECLDIR void Function( void )
{
std::cout << "DLL Called!" << std::endl;
}
}
(3)可选。新建一个WIN32控制台类,测试这个DLL。
文件-》新建-》WIN32控制台->填写项目名称-》选择控制台程序-》空项目-》完成。
在解决方案面板中,加入一个实现文件loaddll.cpp 内容:
代码如下:
#include <iostream>
#include <windows.h>
using namespace std;
typedef int (*AddFunc)(int,int); //定义指针函数、接口。
typedef void (*FunctionFunc)();
int main()
{
AddFunc _AddFunc;
FunctionFunc _FunctionFunc;
cout <<"---获取DLL---."<< endl;
// L 表示使用UNICODE 字符集,要和项目的字符集保持一致。
HINSTANCE hInstLibrary = LoadLibrary(L"E://Project//VS//LoadDll//Release//TestDll.dll");
if (hInstLibrary == NULL)
{
cout <<"Dll 加载【失败】."<< endl;
FreeLibrary(hInstLibrary);
}else{
cout <<"Dll 加载【成功】."<< endl;
}
_AddFunc = (AddFunc)GetProcAddress(hInstLibrary, "Add");
_FunctionFunc = (FunctionFunc)GetProcAddress(hInstLibrary, "Function");
if ((_AddFunc == NULL) || (_FunctionFunc == NULL))
{
FreeLibrary(hInstLibrary);//释放
}else{
cout <<"---获取DLL函数【OK】---."<< endl;
}
cout << _AddFunc(1, 1) << endl; // 开始调用
_FunctionFunc(); //
cin.get(); // 获得焦点,这样就不会程序就不会一闪而过了。
FreeLibrary(hInstLibrary);//调用完后,要释放内存。