我用的是code:blocks
1 创建一个动态链接库工程
main.h
main.cpp
构建完成,生成dll
2 新建一个控制台程序工程
在头文件中增加
在cpp中调用
完成
1 创建一个动态链接库工程
main.h
#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
#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 新建一个控制台程序工程
在头文件中增加
typedef void(*someFunction)(std::string s);
在cpp中调用
#include "wtypes.h"
..
HINSTANCE hDll; //声明一个Dll实例文件句柄
hDll = LoadLibrary("testdll.dll");//testdll.dll动态连接库
someFunction f;
f = (someFunction)GetProcAddress(hDll,"SomeFunction");
f("Hello Dll!");
完成