Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version
Go to top

Dynamic Libraries with Delayed Function Loading

, 27 Oct 2011
This article explains how to create a dynamic library that loads exported functions the first time they are used, opposed to loading them when the library is loaded.
#include <stdio.h>
#include <windows.h>

#include "payload_dll.h"

void test_library(const char *lib_name_sz);
void test_function(HMODULE lib_h, const char *func_name_sz);

int main(int argc, char* argv[])
{
	printf("Delayed Function Loading Example - CLIENT APP\n");

	test_library("payload_dll.dll");
	test_library("proxy_dll.dll");

	return 0;
}

void test_library(const char *lib_name_sz)
{
	printf("\n Trying to load library %s.\n", lib_name_sz);
	HMODULE lib_h = ::LoadLibrary(lib_name_sz);
	
	if (lib_h)
	{
		printf(" Library %s successfully loaded.\n", lib_name_sz);
		
		test_function(lib_h, "add");
		test_function(lib_h, "subtract");
		test_function(lib_h, "multiply");
		test_function(lib_h, "divide");

		::FreeLibrary(lib_h);
		lib_h = NULL;
	}
	else
	{
		printf(" Error loading library %s.\n", lib_name_sz);
	}
}

void test_function(HMODULE lib_h, const char *func_name_sz)
{
	printf("  Searching for function %s.\n", func_name_sz);
	FARPROC func_gen_pf = ::GetProcAddress(lib_h, func_name_sz);
	LP_payload_func func_pf = reinterpret_cast<LP_payload_func>(func_gen_pf);

	if (func_pf)
	{
		printf("  Function %s found.\n", func_name_sz);

		int a = 777;
		int b = 7;

		printf("  Calling function %s with parameters a=%d, b=%d.\n", func_name_sz, a, b);
		int result = (*func_pf)(a, b);
		printf("  Called successfully with result %d.\n", result);
	}
	else
	{
		printf("  Cannot find function %s.\n", func_name_sz);
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under A Public Domain dedication

Share

About the Author

Vasil Bachvarov
Software Developer (Senior)
Bulgaria Bulgaria
Software developer since April 2000.
Active in various areas, most notably C/C++ development with Windows platform, web development, scripting.
Coder by heart.
Interested in higher level software development techniques, abstractions, modeling, software factories.
Nuts and bolts guy.

| Advertise | Privacy | Mobile
Web03 | 2.8.140916.1 | Last Updated 27 Oct 2011
Article Copyright 2011 by Vasil Bachvarov
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid