Remove Ads

Share on Facebook Share on Twitter

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Creating and Using Functions in DLLs
#1
This tutorial is specifically meant for Code::Blocks. The concept is, for the most part, the same with every compiler.

So, why are DLLs useful? If you have a very large application your going to use a considerable amount of system resources. DLLs allow your program to be small and only use functions when needed. This saves your computer a considerable amount of ram only loading functions in DLLs when you need them. This is far more efficient then have a large application with functions the user may never use. That is why you should DLLs in large projects.

Anyway to start create a DLL project. You should have a .cpp and a header.

DLL.h
[code]
#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__
[/code]

DLL.cpp
[code]
#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
}
[/code]

To create your function just change the SomeFunction line to anything you want for your function.
Make sure the .cpp has the same function name(s) as the header.

Dll.h
[code]
void DLL_EXPORT DllFunction();

[/code]
DLL.cpp
[code]
void DLL_EXPORT DllFunction()
{
MessageBox(NULL, "This message was sent from a DLL", "Message", MB_OK );
}[/code]

Now your DLL is complete.

Now i'm going to create a file to use the DllFunction() in the DLL.
[code]
#include <iostream>
#include <windows.h>

typedef void(*DLL_Pointer)();//I will use this pointer to use functions in the dll

HINSTANCE DLL;//For Loading the DLL

int main()
{
DLL_Pointer Func;
DLL = LoadLibrary("DLL.dll");//Load DLL
if(DLL!=NULL)
{
Func = (DLL_Pointer)GetProcAddress(DLL, "DllFunction");//So we can use the DllFunction in the DLL
Func();//The compiler knows what this is, not DllFunction.
}
else
{
std::cout<<"DLL.dll not in the directory...";
std::cin.get();
return 0;
}
FreeLibrary(DLL);//No one likes memory leaks
return 0;
}
[/code]
Reply


Messages In This Thread
Creating and Using Functions in DLLs - by Scorch - 01-15-201111:27 PM

Forum Jump:


Users browsing this thread: 1 Guest(s)