C入门:C调用DLL

来源:互联网 发布:服装设计图软件 编辑:程序博客网 时间:2024/05/21 22:23

header.h:

#ifndef HEADER_H#define HEADER_H#include <windows.h>#include <stdio.h>#include "dll_02.h"int maxInt(int,int);void t1();void testDll();void t2();void testDll01();

impl.cpp:

#include "header.h"void testDll01(){    int x,y;    HINSTANCE hDll;    typedef int (*Fun)(int,int);    Fun fp;    x = 100;    y = 99;    hDll = LoadLibrary("dll_02.dll");    if(NULL == hDll)    {        fprintf(stderr, "load dll 'dll_02.dll' fail.");        return;    }    fp = (Fun)GetProcAddress(hDll, "addxy");    if(NULL == fp)    {        fprintf(stderr, "call function 'addxy' fail.");        FreeLibrary(hDll);        return;    }    fprintf(stdout, "%d+%d=%d\n",x,y,fp(x, y));    FreeLibrary(hDll);}void t2(){    int a = 10;    if(a > 9)    {        fprintf(stderr, "test error.");    }}void testDll(){    HINSTANCE hDll;    typedef void (*Fun)(void);    Fun fp;    hDll = LoadLibrary("dll_02.dll");    if(NULL == hDll)    {        printf("load dll 'dll_02.dll' fail.");        return;    }    fp = (Fun)GetProcAddress(hDll, "hello");    if(NULL == fp)    {        printf("call function 'hello' fail.");        FreeLibrary(hDll);        return;    }    fp();    FreeLibrary(hDll);}void t1(){    typedef int (*Fun)(int,int);    Fun mx;    mx = maxInt;    printf("%d\n", mx(1,20));}int maxInt(int a, int b){    return a>b?a:b;}

main.cpp:
#include "header.h"int main(){    if(1) testDll01();    if(0) t2();    if(0) testDll();    if(0) t1();    return 0;}

Makefile:

buildFiles=header.h impl.cpp main.cppbuild:gcc -x c++ -o .\bin\test $(buildFiles)clean:del .\bin\*.exe