---
title: "创建一个dll文件，并调用"
author: "fourfire"
date: "2010-06-09T21:14:18Z"
tags: []
categories: ["编程语言"]
slug: "dll"
draft: false
lastmod: "2010-06-09T21:14:18Z"
id: 688361
url: "https://fourfire.iteye.com/blog/688361"
---

我用的是code:blocks
1 创建一个动态链接库工程
main.h

```c++

#ifndef __MAIN_H__
#define __MAIN_H__

#include <windows.h>
#include <string>
/*  To use this exported function of dll, include this header
 *  in your project.
 */

#ifdef BUILD_DLL
    #define DLL_EXPORT __declspec(dllexport)
#else
    #define DLL_EXPORT __declspec(dllimport)
#endif


#ifdef __cplusplus
extern "C"
{
#endif
//函数的形式
void DLL_EXPORT SomeFunction(const std::string sometext);

#ifdef __cplusplus
}
#endif

#endif // __MAIN_H__


```

main.cpp

```c++

#include "main.h"
#include <iostream>
#include <string>
// 这里是一个例子函数
void DLL_EXPORT SomeFunction(const std::string s)
{
    std::cout<<s<<std::endl;
}

BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
    switch (fdwReason)
    {
        case DLL_PROCESS_ATTACH:
            // attach to process
            // return FALSE to fail DLL load
            break;

        case DLL_PROCESS_DETACH:
            // detach from process
            break;

        case DLL_THREAD_ATTACH:
            // attach to thread
            break;

        case DLL_THREAD_DETACH:
            // detach from thread
            break;
    }
    return TRUE; // succesful
}

```

构建完成，生成dll
2 新建一个控制台程序工程
在头文件中增加

```c++

typedef void(*someFunction)(std::string s);

```

在cpp中调用

```c++

#include "wtypes.h"
..
 HINSTANCE hDll; //声明一个Dll实例文件句柄
hDll = LoadLibrary("testdll.dll");//testdll.dll动态连接库
someFunction f;
f = (someFunction)GetProcAddress(hDll,"SomeFunction");
f("Hello Dll!");

```

完成