C语言运行时调用.so库

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_43138570/article/details/102608127

实例:
函数介绍:
#include <dlfcn.h>

   void *dlopen(const char *filename, int flag);
   参数介绍:
   		filename 动态库路径
   		flag 标志
   			RTLD_LAZY 暂缓决定,等有需要时再解出符号 
			RTLD_NOW 立即决定,返回前解除所有未决定的符号。 
			RTLD_LOCAL 
			RTLD_GLOBAL 允许导出符号 (本库中的symbol对于后续要被加载的库是可见的)
			RTLD_GROUP 
			RTLD_WORLD 

   char *dlerror(void);

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

   int dlclose(void *handle);
#include <stdio.h>

typedef struct Module{                                                                                         
    int          version;
    int          minor_version;
    const char  *name;
    void (*init)(Module *); 
    int (*handle)(void *); 
} Module;

static int handler(void * data) {
    printf("-------- handler...\n");
    return 0;
}

static void init(Module *mod)
{
    printf("-------- init...\n");
}

Module savehtml = { 
    init,
    handler
};

编译:

gcc -shared -fPIC -o libmodule.so module.c
#include <dlfcn.h>
#include <stdio.h>

typedef struct Module{                                                                                         
    int          version;
    int          minor_version;
    const char  *name;
    void (*init)(Module *); 
    int (*handle)(void *); 
} Module;

int main(int argc, char** argv){
	void *rv = NULL;
    void *handle = NULL;
    Module *module = NULL;

	char* path = argv[1];    //动态库路径
	char* name = argv[2];    //动态库名字(不需要加上.so后缀)
	
    char * npath = strcat2(3, path, name, ".so");

    if ((handle = dlopen(npath, RTLD_GLOBAL | RTLD_NOW)) == NULL) { 
        SPIDER_LOG(SPIDER_LEVEL_ERROR, "Load module fail(dlopen): %s", dlerror());
    }   
    if ((rv = dlsym(handle, name)) == NULL) {
        SPIDER_LOG(SPIDER_LEVEL_ERROR, "Load module fail(dlsym): %s", dlerror());
    }   
    module = (Module *)rv;
    module->init(module);
    module->handler(NULL);
    dlclose(handle);
	
	return 0;
}

运行结果:

gcc -rdynamic -o main main.c -ldl
./main ./ libmodule
-------- init...
-------- handler...

猜你喜欢

转载自blog.csdn.net/weixin_43138570/article/details/102608127