Skip to content Skip to footer

VC中调用dll函数的两种方法

一、显式调用1、定义函数指针 typedef int (*dll_mul)(int a,int b);2、加载dll,并获取其程序实例句柄HINSTANCE hdll=loadlibrary("c:/cppDll.dll");3、从dll实例句柄中获取函数指针dll_mul mymul=(dll_mul)GetProcAddress(hdll,"mul");4、使用获取的函数int sum=mymul(5,6);

源代码如下:

#include "stdafx.h"

#include "windows.h"

typedef int(*dll_add)(int a,int b);//定义函数指针

int _tmain(int argc, _TCHAR* argv[])

{

HINSTANCE hDll=LoadLibrary("c:/CppDll.dll");//加载dll并获取实例句柄

dll_add myadd=(dll_add)GetProcAddress(hDll,"mul");//找到函数地址

int sum=myadd(5,6);

printf("sum=%d",sum);

system("pause");

return 0;

}

二、隐式调用

1、将cppDll.dll拷贝至系统环境变量中指定的位置,如C:\Windows\System32。

2、声明dll中的函数

int div(int a,int b);

3、导入CppDll.lib静态链接库,通过lib获取函数在dll中的偏移地址,从而找到函数

#pragma comment(lib,"c:/CppDll.lib");

4、使用函数

int num=div(6,2);

源代码如下:

#include "stdafx.h"

#include "windows.h"

int mul(int a,int b);//声明函数

#pragma comment(lib,"c:/CppDll.lib");// 导入lib函数,获取函数的偏移地址

int _tmain(int argc, _TCHAR* argv[])

{

int num=mul(2,3);//使用函数

printf("num=%d",num);

system("pause");

return 0;

}

Copyright © 2088 世界杯射手榜_2014世界杯16强对阵表 - panlongs.com All Rights Reserved.
友情链接