Home >Backend Development >C++ >How to Dynamically Load and Call Functions from DLLs in C ?

How to Dynamically Load and Call Functions from DLLs in C ?

Barbara Streisand
Barbara StreisandOriginal
2024-12-08 11:29:10764browse

How to Dynamically Load and Call Functions from DLLs in C  ?

Dynamic Loading of Functions from DLLs

Loading functions dynamically from DLLs (Dynamic Link Libraries) in C allows you to access functionality defined in separate modules at runtime. Here's how to approach this problem:

1. Load the DLL:

<br>HINSTANCE hDLL = LoadLibrary("path/to/dll.dll");<br>

This step loads the DLL into memory and returns a handle to it.

2. Get the Function Pointer:

To access a function within the DLL, you need to obtain its address using GetProcAddress:

<br>typedef int (__stdcall *f_funci)(); // Define function pointer type<br>f_funci funci = (f_funci)GetProcAddress(hDLL, "funci");<br>

This example assumes your function is named "funci" and uses the __stdcall calling convention.

3. Calling the Function:

Once you have the function pointer, you can call the function like any other function:

<br>int result = funci();<br>

4. Exporting the Function from the DLL:

In the DLL, your function must be exported using __declspec(dllexport) to make it accessible to other modules:

<br>int __declspec(dllexport) __stdcall funci() {<br>   // Function definition<br>}<br>

Additional Tips:

  • It's advisable to free the DLL handle using FreeLibrary() when it's no longer needed.
  • Use a function pointer type that accurately matches the function's signature in the DLL.
  • Ensure proper error handling to handle any issues with DLL loading or function resolution.

The above is the detailed content of How to Dynamically Load and Call Functions from DLLs 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