C++: How to create a DLL and calling it from application?
I create the DLL first,
Main.h
#ifndef __MAIN_H__
#define __MAIN_H__
#include <windows.h>
/* 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 LPCSTR sometext);
#ifdef __cplusplus
}
#endif
#endif // __MAIN_H__
Main.cpp
#include "main.h"
// a sample exported function
void DLL_EXPORT SomeFunction(const LPCSTR sometext)
{
MessageBoxA(0, sometext, "DLL Message", MB_OK | MB_ICONINFORMATION);
}
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
}
Build the DLL then create the application to call the function. You must put the correct DLL path.
#include <iostream>
#include <windows.h>
using namespace std;
// pointer to function in dll, caller of CallDll
typedef __declspec(dllimport)DWORD(*pfFunc)(const LPCSTR sometext);
int main()
{
HINSTANCE hDll = ::LoadLibrary("D:\\ bin\\Debug\\araoarao.dll"); // put your own DLL path here
pfFunc pFun = NULL;
pFun = (pfFunc)::GetProcAddress(hDll, "SomeFunction");
pFun("Hello World!!");
return 0;
}
After successful linking when you run the application it will display a message box with "Hello World"
Thant's it!
Comments
Post a Comment