现在的位置: 首页 > 综合 > 正文

函数的DLL调用方式

2013年05月10日 ⁄ 综合 ⁄ 共 1664字 ⁄ 字号 评论关闭

方式一:rundll32.exe

先在CMD中试试

rundll32 shell32.dll, OpenAs_RunDLL ---对某个文件右键->打开方式

rundll32 shell32.dll,Control_RunDLL desk.cpl,,1 --- 开始->设置->控制面板->外观-> 显示->屏幕保护

rundll32 user.exe,restartwindows ---重启机器,此处说明不要被后缀名迷惑,windows 自己的规范连自己都不遵守,可能是为了兼容吧。

自己做个DLL如何?

/*
file:lib.c
compile: mingw-gcc --shared lib.c -o lib.dll
test: rundll32 lib.dll,fun
rundll32 lib.dll,foo xx

但是调用foo xx 出错,多rundll 几次可以看到消息盒子,但正文 就全是乱码了,
首先怀疑是Unicode问题,但是细想main.c (见后文)没出问题呀;是不是Rundll32 本身没有
把参数传递正确?
通过在线的MSDN找到答案:原来rundll32 对接口有要求,并且逗号两边不能有空格。
增加这样的接口xyz,

编译,然后执行命令 rundll32 lib.dll,xyz xxxxxxxxxxxxxxx 就没问题了。

注记1:也可用VC6 编译:
CL.exe /LD lib.c user.lib
实际上,宏DLL也是他要求的。另外 $ gcc -mno-cygwin -v
这是3.44 版,可以编译但编译的dll似乎有问题。

注记2:所谓的DLL入口函数DllMain 不是必须的,下面把它改成了DllMai。

*/

#include<windows.h>
#include<stdio.h>

#define DLL __declspec(dllexport)

DLL int foo(char *s)
{
MessageBox(NULL,s,"foo",MB_OK);
printf("dll get %s/n",s);
return 0;
}

DLL int fun(void)
{
MessageBox(NULL,"hello","fun",MB_OK);
printf("fun/n");
return 0;
}

DLL void xyz(HWND hwnd,HINSTANCE hinst,
LPSTR cmd,int show)
{
MessageBox(NULL,(char*)cmd,"xyz",MB_OK);
}

BOOL WINAPI DllMai(HINSTANCE mod,DWORD reason,LPVOID reserved)
{
if(reason == DLL_PROCESS_ATTACH)
{
printf("process attached/n");
}
else if(reason == DLL_PROCESS_DETACH)
{
printf("process detached/n");
}
else if(reason == DLL_THREAD_ATTACH)
{
printf("thread attached/n");
}
else if(reason == DLL_THREAD_DETACH)
{
printf("thread detached/n");
}
return TRUE;
}

方式二:手动装载

/*
file:main.c

*/
#include<windows.h>
#include<stdio.h>

typedef int (*FOO)(char *s);
int main()
{
HMODULE mod;
FOO foo;

mod = LoadLibrary("lib.dll");

if(foo=(FOO)GetProcAddress(mod,"foo"))
foo("hello,world");

FreeLibrary(mod);

return 0;
}

本文参考了http://code.google.com/p/msys-cn/wiki/Chapter5

Linux系统下相对应的函数为:dlopen,dlsym,dlclose,请参考http://dev.csdn.net/htmls/84/84562.html

 

抱歉!评论已关闭.