Home > Backend Development > C++ > How to Access DLL Functions Using LoadLibrary and GetProcAddress?

How to Access DLL Functions Using LoadLibrary and GetProcAddress?

Mary-Kate Olsen
Release: 2024-12-11 12:36:13
Original
582 people have browsed it

How to Access DLL Functions Using LoadLibrary and GetProcAddress?

Dynamically Loading Functions from DLLs

Question:

How can the LoadLibrary handle be used to access functions defined in a DLL?

LoadLibrary loads a DLL into memory but does not automatically import its functions. This requires a second WinAPI function: GetProcAddress.

Example:

#include <windows.h>
#include <iostream>

typedef int (__stdcall *f_funci)();

int main()
{
  HINSTANCE hGetProcIDDLL = LoadLibrary("C:\Documents and Settings\User\Desktop\test.dll");

  if (!hGetProcIDDLL) {
    std::cout << "could not load the dynamic library" << std::endl;
    return EXIT_FAILURE;
  }

  // Resolve function address using GetProcAddress
  f_funci funci = (f_funci) GetProcAddress(hGetProcIDDLL, "funci");
  if (!funci) {
    std::cout << "could not locate the function" << std::endl;
    return EXIT_FAILURE;
  }

  std::cout << "funci() returned " << funci() << std::endl;
  
  // Free the library handle when no longer needed
  FreeLibrary(hGetProcIDDLL);
  
  return EXIT_SUCCESS;
}
Copy after login

Dll Export:

Ensure the function is correctly exported from the DLL using the __declspec(dllexport) and __stdcall attributes:

int __declspec(dllexport) __stdcall funci() {
   // ...
}
Copy after login

The above is the detailed content of How to Access DLL Functions Using LoadLibrary and GetProcAddress?. 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