C++

The C language parses the process of loading dynamic link libraries from code


This article mainly introduces the process of C language loading dynamic link library from the code analysis, the article through the example code introduction is very detailed, for everyone’s study or work has a certain reference learning value, friends in need can refer to

void *dlopen(const char *filename, int flag);

Function: Open dynamic link library file

Parameter: filename dynamic link library file name

flag open mode, 1 generally RTLD_LASY

Return value: library pointer

Function: char *dlerror(void);

Function: Get error value

Return value: Error value

void *dlsym(void *handle, const char *symbol);

Function: Gets a pointer to a specified function in the dynamic link library

Parameter: handle library pointer

symbol function name

Return value: A pointer to the function corresponding to the parameter symbol name

int dlclose(void *handle);

Function: Close the dynamic link library file

Parameter: library pointer

The return value:

The source code

/*main.c*/
#include <dlfcn.h>//  The associated function header file
#include <stdio.h>

int main(void)
{
  const char *src = "Hello Dymatic";
  int (*pStrLen)(const char *);//  A function pointer
  void *pHandle = NULL;//  Library pointer
  char *pErr = NULL;//  Error pointer

  //  Open the dynamic link library and check for errors
  pHandle = dlopen("./libstr.so " , RTLD_LASY);
  pErr = dlerror();
  if(!pHandle || pErr != NULL){printf("Failed load library!\n%s\n", pErr);return -1;}

  //  To obtain StrLen Function address and check for errors
  pStrLen = dlsym(pHandle, "StrLen");
  pErr = dlerror();
  if(!pStrLen || pErr == NULL){printf("%s\n", pErr);return -1;}

  //  call StrLen function
  printf("The string length is:%d\n", pStrLen(src));

  //  Close library files
  dlclose(pHandle);
  return 0;
]

Run the following command to compile it into an executable. -ES86en./ Current directory, -lstr is the library file of StrLen function, -ES89en is the library file of dlopen and other related functions

gcc -o test main.c -L./ -lstr -ldl