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
Mary-Kate OlsenOriginal
2024-12-11 12:36:13557browse

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;
}

Dll Export:

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

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

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!

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