Home >Backend Development >C++ >How Can I Dynamically Load and Use Functions from a DLL in C ?

How Can I Dynamically Load and Use Functions from a DLL in C ?

Susan Sarandon
Susan SarandonOriginal
2024-12-20 14:28:10379browse

How Can I Dynamically Load and Use Functions from a DLL in C  ?

Dynamically Load a Function from a DLL

Introduction

Dynamic linking allows you to load a function from a DLL during runtime, extending the functionality of your program. This article will guide you on how to accomplish this.

Loading the DLL

The first step is to load the DLL into the memory of the current process. This is done using the LoadLibrary function:

HINSTANCE hGetProcIDDLL = LoadLibrary("path/to/test.dll");

Getting the Function Address

Once the DLL is loaded, you need to locate the address of the function you want to call. For this, we use the GetProcAddress function:

typedef int (__stdcall *f_funci)();
f_funci funci = (f_funci)GetProcAddress(hGetProcIDDLL, "funci");

Note that you need to define a function pointer type that matches the signature of the exported function. In our case, it's a function returning an integer and taking no arguments.

Exporting the Function from DLL

For the DLL to be loaded successfully, you need to export the function correctly. Add the following to your DLL's source code:

int __declspec(dllexport) __stdcall funci() {
  // ...
}

Using the Function

Once the function's address is obtained, you can call it like any other function:

std::cout << "funci() returned " << funci() << std::endl;

Releasing the DLL Handle

For resource cleanup, it's good practice to release the DLL handle when not needed anymore:

FreeLibrary(hGetProcIDDLL);

By following these steps, you can dynamically load and use functions from DLLs, significantly enhancing the flexibility and extensibility of your program.

The above is the detailed content of How Can I Dynamically Load and Use Functions from a DLL in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn