C入门:C调用DLL

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.cpp

build:
	gcc -x c++ -o .\bin\test $(buildFiles)
clean:
	del .\bin\*.exe



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值