Get the App
SLTechnology News&Howtos  ›  Network Security  › 

How dlopen and dlsym call functions dynamically

Shulou Source: shulou.com Published: 2022-05-31 23:38:46 10月03日 Update

This article mainly introduces dlopen and dlsym how to call functions dynamically, the article is very detailed, has a certain reference value, interested friends must read it!

Linux/unix provides dynamic loading libraries and calling functions using dlopen and dlsym methods, which are also supported on macOS and iOS.

Dlopen opens a library and gets the handle.

Dlsym looks for the value of the symbol in the open library.

Dlclose closes the handle.

Dlerror returns a string describing the error message of the last call to dlopen, dlsym, or dlclose.

Call the printf function dynamically, and write the test code as follows:

# import typedef int (* printf_func_pointer) (const char * _ restrict,...); void dynamic_call_function () {/ / dynamic library path char * dylib_path = "/ usr/lib/libSystem.dylib"; / / Open dynamic library void * handle = dlopen (dylib_path, RTLD_GLOBAL | RTLD_NOW) If (handle = = NULL) {/ / error opening dynamic library fprintf (stderr, "% s\ n", dlerror ());} else {/ / get printf address printf_func_pointer printf_func = dlsym (handle, "printf"); / / call if (printf_func) {int num = 100 if the address is obtained successfully Printf_func ("Hello exchen.net% d\ n", num); printf_func ("printf function address 0x%lx\ n", printf_func);} dlclose (handle); / / close handle}} int main (int argc, char * argv []) {@ autoreleasepool {dynamic_call_function () Return UIApplicationMain (argc, argv, nil, NSStringFromClass ([AppDelegate class]);}}

The output of running on the phone is as follows:

Hello exchen.net 100printf function address 0x189f0da78 above is all the content of the article "how to call functions dynamically by dlopen and dlsym". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Tags: Dynamic function handle content address method article success code value information interest character string boy buddy more knowledge symbol result Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux macOS Apple Shulou Tech Info Redmi