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
Release: 2024-12-20 14:28:10
Original
379 people have browsed it

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");
Copy after login

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");
Copy after login

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() {
  // ...
}
Copy after login

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;
Copy after login

Releasing the DLL Handle

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

FreeLibrary(hGetProcIDDLL);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template