Shared Library
V1.0
email: mesmerli@hotmail.com
dltest.c (呼叫 Shared Library)
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <dlfcn.h>
#include <ctype.h>
typedef void (*func_t) (const char *);
void dltest(const char *s)
{
printf("From dltest:");
for(; *s; s++)
{
putchar(toupper(*s));
}
putchar('n');
}
int main(int argc, char **argv)
{
void *handle;
func_t fptr;
char *libname = "./libfoo.so";
char **name = NULL;
char *funcname = "foo";
char *param = "Dynamic Loading Test";
int ch;
int mode = RTLD_LAZY;
while((ch = getopt(argc, argv, "a:b:f:l:")) != EOF)
{
switch(ch)
{
case 'a': // argument
param = optarg;
break;
case 'b': // how to bind
switch(*optarg)
{
case '1': //lazy
mode = RTLD_LAZY;
break;
case 'n': // now
mode = RTLD_NOW;
break;
}
break;
case 'l': // which shared library
libname = optarg;
break;
case 'f': // which function
funcname = optarg;
}
}
// open libfoo.so
handle = dlopen(libname, mode);
if(handle == NULL)
{ // open failed
fprintf(stderr, "%s:dlopen:'%s'n", libname, dlerror());
exit(1);
}
// call dlsym lib functions to get pointers of foo or bar function in libraries
fptr = (func_t)dlsym(handle, funcname);
if(fptr == NULL)
{ // failed to get function pointers
fprintf(stderr, "%s:dlsym:'%s'n", funcname, dlerror());
exit(1);
}
// get lib name
name = (char **) dlsym(handle, "libname");
if(name == NULL)
{ // failed to get lib name
fprintf(stderr, "%s:dlsym:'libname'n", dlerror());
exit(1);
}
printf("Call '%s' in '%s':n", funcname, *name);
// call foo or bar function with 'param'parameters
(*fptr)(param);
dlclose(handle);
return 0;
}
libfoo.c (Shared Library NO.1)
#include <stdio.h>
extern void dltest(const char *s);
const char *const libname = "libfoo.so";
void foo(const char *s)
{
const char *saved = s;
dltest("Called from libfoo");
printf("libfoo:");
for(; *s; s++);
for(s--; s>=saved; s--)
{
putchar(*s);
}
putchar('n');
}
libbar.c (Shared Library NO.2)
#include <stdio.h>
extern void dltest(const char *);
const char * const libname = "libbar.so";
void bar(const char *s)
{
dltest("Called from libbar.");
printf("libbar:%sn",s);
}
Makefile_Cross
CC = arm-linux-gcc
LDFLAGS=-rdynamic
SHLDFLAGS=
RM=rm
all:dltest_Cross.exe
libfoo_Cross.o:libfoo.c
$(CC) -o $@ -c -fPIC $<
libfoo_Cross.so:libfoo_Cross.o
$(CC) $(SHLDFLAGS) -shared -o $@ $^
libbar_Cross.o:libbar.c
$(CC) -o $@ -c -fPIC $<
libbar_Cross.so:libbar_Cross.o
$(CC) $(SHLDFLAGS) -shared -o $@ $^
dltest_Cross.o:dltest.c
$(CC) -o $@ -c $^
dltest_Cross.exe: dltest_Cross.o libbar_Cross.so libfoo_Cross.so
$(CC) $(LDFLAGS) -o $@ dltest_Cross.o -ldl
clean:
$(RM) *.o *.so *.exe
0 意見:
張貼留言