Home > Backend Development > C++ > How to Dynamically Load and Call a Function from a DLL in C ?

How to Dynamically Load and Call a Function from a DLL in C ?

Patricia Arquette
Release: 2024-12-12 22:58:14
Original
660 people have browsed it

How to Dynamically Load and Call a Function from a DLL in C  ?

Dynamically Loading a Function from a DLL

Question:

You have created a DLL with a function named funci() and are attempting to load and access this function from C . However, you encounter the error "'funci' was not declared in this scope." How can you use the DLL's pointer to access the function?

Answer:

Step 1: Load the DLL

HINSTANCE hGetProcIDDLL = LoadLibrary("C:\path\to\test.dll");
Copy after login

This loads the DLL into the process's memory.

Step 2: Resolve Function Address

You need to get the function's address using GetProcAddress.

typedef int (__stdcall *f_funci)(); // Define function pointer
f_funci funci = (f_funci)GetProcAddress(hGetProcIDDLL, "funci");
Copy after login

Step 3: Verify Function Address

Check if the function address was obtained successfully.

if (!funci) {
  std::cout << "Could not locate the function" << std::endl;
  return EXIT_FAILURE;
}
Copy after login

Step 4: Call the Function

Once you have the function pointer, you can call it.

std::cout << "funci() returned " << funci() << std::endl;
Copy after login

Step 5: Freeing the DLL (Optional)

Release the DLL handle using FreeLibrary() to unload the DLL from memory.

FreeLibrary(hGetProcIDDLL);
Copy after login

Additional Tips:

  • The WinAPI function GetProcAddress requires the function name as a string, so make sure to specify the correct name.
  • The calling convention of the exported function (e.g., __stdcall) must match the one used when defining the function pointer in your program.
  • Properly exporting functions from the DLL is essential. Use the __declspec(dllexport) attribute to export the function.

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