2017年4月17日 星期一
dlopen and dlsym
Prepare a SO file writtern in C:
vi libso.c
#include <stdio.h>
int bejo_lib(char *name, int i) {
printf("I am %s, do i=%d\n", name, i);
return 0;
}
gcc -fPIC -c libso.c
gcc -shared -o libso.so libso.o
Notice the function name is not mangled because it is not C++:
nm libso.so | grep bejo
00000000000006c8 T bejo_lib
Prepare the C user code:
vi use.c
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
int main(int argc, char **argv) {
void* so = dlopen("./libso.so",RTLD_LAZY);
printf("so: %p\n", so);
if (!so) {
fprintf(stderr, "%s\n", dlerror());
exit(1);
}
dlerror();
void (*fn)();
fn = (void(*)())dlsym(so, "bejo_lib");
printf("fn: %p\n", fn);
if (fn) {
fn("BEJO", 999);
}
dlclose(so);
return 0;
}
// nm libso.so | grep bejo
// 00000000000006c8 T bejo_lib
// gcc use.c -ldl -o use && ./use
The functions are mangled in the SO file libEsunnyQuot.so written in C++:
nm libEsunnyQuot.so | grep CreateEsunnyQuotClient
0000000000007c60 T _Z22CreateEsunnyQuotClientP17IEsunnyQuotNotify
nm libEsunnyQuot.so | grep DelEsunnyQuotClient
0000000000007c30 T _Z19DelEsunnyQuotClientP17IEsunnyQuotClient
Prepare the C++ user code:
vi sun.cpp
#include "EsunnyQuot.h"
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
int main(int argc, char **argv) {
void* so = dlopen("./libEsunnyQuot.so",RTLD_LAZY);
printf("so: %p\n", so);
if (!so) {
fprintf(stderr, "%s\n", dlerror());
exit(1);
}
dlerror();
void (*fn)(IEsunnyQuotClient*);
fn = (void(*)(IEsunnyQuotClient*))dlsym(so, "_Z19DelEsunnyQuotClientP17IEsunnyQuotClient");
printf("fn: %p\n", fn);
if (fn) {
fn(NULL);
}
dlclose(so);
return 0;
}
// nm libEsunnyQuot.so | grep CreateEsunnyQuotClient
// 0000000000007c60 T _Z22CreateEsunnyQuotClientP17IEsunnyQuotNotify
// nm libEsunnyQuot.so | grep DelEsunnyQuotClient
// 0000000000007c30 T _Z19DelEsunnyQuotClientP17IEsunnyQuotClient
// gcc sun.cpp -ldl -o sun && ./sun
訂閱:
張貼留言 (Atom)
2023 Promox on Morefine N6000 16GB 512GB
2023 Promox on Morefine N6000 16GB 512GB Software Etcher 100MB (not but can be rufus-4.3.exe 1.4MB) Proxmox VE 7.4 ISO Installer (1st ISO re...
-
On CentOS 7, using yum install gives you cmake version 2.8.11 [root@thrift1 ~]# cat /etc/*release CentOS Linux release 7.2.1511 (Core) ...
-
Synology DSM 5.2 on Virtual Box Files On my Google Drive "2016DSM5.2" or download link below (3 files total: pat, iso, exe) ...
-
Static ZeroMQ (difficult setup) cd /d C:\ mkdir Repos cd /d C:\Repos\ git clone https://github.com/Microsoft/vcpkg cd /d C:\Repos\v...
沒有留言:
張貼留言