Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- build shared library:
- gcc -fPIC -c testas.c
- ld -shared -soname libtestas.so.1 -o libtestas.so.1.0 -lc testas.o
- testas.c:
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdbool.h>
- void _init()
- {
- printf("init\n");
- }
- void _fini()
- {
- printf("fini\n");
- }
- void fncG()
- {
- printf("test 2\n");
- }
- */
- //main.c:
- //-std=c99 -Wall -Wextra -Wpedantic -Wshadow
- //linking: -ldl -Wl,-rpath=.
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdbool.h>
- #include <string.h>
- #include <dlfcn.h>
- void fncA()
- {
- printf("test\n");
- }
- int fncB(int x, int y)
- {
- return x + y;
- }
- void *fncC(void *p)
- {
- return p;
- }
- int fnc(int x)
- {
- return x+1;
- }
- char fncc(char c)
- {
- return c+1;
- }
- //typedef char (*PFC)(); warning: return from incompatible pointer type
- typedef char (*PFC)(char);
- char testF1(char a)
- {
- return a+1;
- }
- char testF2(char a)
- {
- return a+2;
- }
- PFC pfAddr(bool b)
- {
- if (b) return &testF1;
- return &testF2;
- }
- int main (int argc, char **argv)
- {
- int result;
- //notes:
- //the unary operator & is optional
- //to make code more portable, you should always use &
- //when assigning an address of a function to a function pointer
- void(*pf_fncA)()=&fncA; //=fncA;
- int(*pf_fncB)()=&fncB; //=fncB;
- void *(*pf_fncC)();
- (*pf_fncA)();
- pf_fncA();
- result = (*pf_fncB)(1,2);
- printf("%d\n",result);
- pf_fncC = &fncC; //=fncC;
- printf("%p\n",(void*)&result);
- void *pResult = pf_fncC(&result);
- printf("%p\n",pResult);
- int (*fp)(int);
- fp = fnc;
- printf("%d\n",fp(1));
- printf("%d\n",(*fp)(1));
- char (*fpc)(char);
- //fpc = fncc;
- fpc = &fncc;
- printf("%c\n",fpc('a'));
- printf("%c\n",(*fpc)('b'));
- PFC pFTest;
- pFTest = pfAddr(true);
- printf("%c\n",pFTest('a'));
- pFTest = pfAddr(false);
- printf("%c\n",pFTest('a'));
- char *err;
- void *lib = dlopen("libtestas.so.1.0", RTLD_NOW);
- if (!lib)
- {
- printf("%s\n", dlerror());
- return 1;
- }
- dlerror();
- printf("INFO: load lib OK.\n");
- //warning: ISO C forbids initialization between function pointer and ‘void *’
- //void(*pfVoid)() = dlsym(lib, "fncG");
- void(*pfVoid)();
- *(void **)(&pfVoid) = dlsym(lib, "fncG");
- if ( (err = dlerror()) != NULL)
- {
- printf("%s\n", err);
- dlclose(lib);
- return 1;
- }
- //function must be called before dlclose(lib), or there will be a segfault
- pfVoid();
- dlclose(lib);
- printf("INFO: exit OK.\n");
- return 0;
- }
- /*
- output:
- test
- test
- 3
- 0x7ffe780bbff4
- 0x7ffe780bbff4
- 2
- 2
- b
- c
- b
- c
- init
- INFO: load lib OK.
- test 2
- fini
- INFO: exit OK.
- */
Advertisement
Add Comment
Please, Sign In to add comment