使用 CodeBlocks 新建一个 DLL 工程,在生成的
源代码中更改函数的声明为__stdcall,新建一个 Def 文 件在文件中声明要导出的函数,这样就 OK 了! 下面贴出来示例的代码: main.h C++代码 代码
1. 2. 3. 4. 5. 6. 7. 8. 9.
#ifndef __MAIN_H__ #define __MAIN_H__
#include
/* * */
To use this exported function of dll, include this header in your project.
10. //#ifdef BUILD_DLL 11. // #define DLL_EXPORT __declspec(dllexport)
12. //#else 13. // #define DLL_EXPORT __declspec(dllimport)
14. //#endif 15. 16. #ifdef __cplusplus 17. extern "C" 18. { 19. #endif 20. void __stdcall SomeFunction(const LPCSTR sometext); 21. int __stdcall SayHello(const LPCSTR lpCaption, const LPCSTR lpText);
22. #ifdef __cplusplus 23. }
24. #endif 25. 26. #endif // __MAIN_H__
main.cpp C++代码 代码
1. 2. 3. 4. 5. 6.
#include "main.h"
// a sample exported function void __stdcall SomeFunction(const LPCSTR sometext) { MessageBoxA(0, sometext, "DLL Message", MB_OK | MB_ICONINFORMATIO N);
7. 8. 9. 10. 11. 12.
} int __stdcall SayHello(const LPCSTR lpCaption, const LPCSTR lpText) { MessageBoxA(0, lpText, lpCaption, MB_OK | MB_ICONINFORMATION); return 0;
13. } 14. BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvRes erved) 15. { 16. 17. 18. 19. 20. 21. switch (fdwReason) { case DLL_PROCESS_ATTACH: // attach to process // return FALSE to fail DLL load break;
22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. } } return TRUE; // succesful case DLL_THREAD_DETACH: // detach from thread break; case DLL_THREAD_ATTACH: // attach to thread break; case DLL_PROCESS_DETACH: // detach from process break;
Def 文件 C++代码 代码
1. 2. 3.
EXPORTS SomeFunction SayHello
在 CodeBlocks 里设置项目的 build option 中 linker Settings 的 Other Link Options 中添加上你写的 Def 文件的文件名,比如"MyDll.def”。这样编译好以后的 dll 就可以供 Delphi 使用了。 这里贴出在 Delphi 中静态调用 DLL 中函数的部分代码: Delphi 代码
1. 2. 3. implementation
4. 5.
{$R *.dfm} procedure SomeFunction(const sometext: PChar); stdcall; external 'Dll 的名称.dll';
6.
function SayHello(const lpCaption: PChar; const lpText: PChar):Intege r; stdcall; external 'Dll 的名称.dll';
声明以后就可以在程序中调用了!其实和 VC 生成的 DLL 供 Delphi 使用是差不多的!