[WinAPI] Initializare automatica pentru dll-uri (Win32/C++)

Folosire Windows API in programe C/C++ (forum moderat)
Post Reply
User avatar
cristianamarie
Membru++
Membru++
Posts: 480
Joined: 12 Mar 2009, 18:47
Judet: Iaşi
Location: Iasi

[WinAPI] Initializare automatica pentru dll-uri (Win32/C++)

Post by cristianamarie » 27 Jan 2010, 15:56

Problema
La un anume nivel al unei aplicatii (global sau la nivel de functie) este necesara initializarea unui dll.

Raspuns
Folosind o clasa automatica pentru a asigura lifetime-ul unui dll, ca in exemplul:

Code: Select all

class Dll
{
private:
	HMODULE  m_hDll;
	SHString m_sDllName;
public:
	Dll(LPCWSTR lpDllName) {
		m_hDll = NULL;
		if((lpDllName != NULL) 
			&& (lstrlenW(lpDllName) > 0)) {
			m_hDll = ::LoadLibraryW(lpDllName);
			m_sDllName = lpDllName; } }
	~Dll() {
		HMODULE hDll = m_hDll;
		m_hDll = NULL;
		if(hDll != NULL) {
			::FreeLibrary(hDll); } }
private:
	Dll(const Dll&);
	Dll& operator=(const Dll&);
public:
	const LPCWSTR GetDllName() const {
		return m_sDllName; }
	operator HMODULE() {
		return m_hDll; }
	operator bool () const {
		return m_hDll != NULL; }
	bool operator !() const {
		return m_hDll == NULL; }
};
Folosirea poate fi parte a intializarii in (w)main, WinMain, DllMain etc.

Code: Select all

int wmain(int argc, 
		  wchar_t **argv) {
	Dll richeditDll(L"riched20.dll");
	return 0;
}
sau la nivel global:

Code: Select all

static Dll richeditDll(L"riched20.dll");

int wmain(int argc, 
		  wchar_t **argv) {
	return 0;
}
Nota: numele dll-ului (variabila Dll::m_sDllName) foloseste o clasa simpla SHString (am evitat CStringW pentru a nu depinde de MFC sau ATL). Implementarea ei foloseste functii COM si din SHLwApi.dll (in treacat fie spus, se poate si imbunatati...):

Code: Select all

#include <windows.h>
#include <shlwapi.h>

#pragma comment(lib, "shlwapi.lib")

class SHString {
	private:
		LPWSTR _pStr;
	public:
		SHString() {
			_pStr = NULL; }
		explicit SHString(LPCWSTR p) {
			_pStr = NULL;
			_Copy(p); }
		explicit SHString(const SHString& src) {
			_pStr = NULL;
			_Copy(src); }
		~SHString() {
			_Clear(); }
	public:
		SHString& operator=(LPCWSTR p) {
			_Clear();
			_Copy(p);
			return *this; }
		SHString& operator=(const SHString& src) {
			_Clear();
			_Copy(src);
			return *this; }
		operator LPCWSTR() const {
			return (LPCWSTR)_pStr; }
	private:
		void _Copy(LPCWSTR p) {
			if(p != NULL) {
				::SHStrDupW(p, &_pStr); } }
		void _Copy(const SHString& src) { 
			if(src._pStr != NULL) {
				::SHStrDupW(src._pStr, &_pStr); } }
		void _Clear() {
			LPWSTR p = _pStr;
			_pStr = NULL;
			if(p != NULL) {
				::CoTaskMemFree(p); } }
};

// ==> ... codul Dll de mai sus

<< Back to Windows API Index


Nuclear launch detected

Post Reply