扩展动态链接共享库?

我是C的新人,很抱歉我缺乏知识(我的C-book非常庞大:)

我想扩展一个共享库(libcustomer.so)与封闭源,但公众已知api。

这样的事情可能吗?

  1. 将libcustomer.so重命名为liboldcustomer.so
  2. 创建一个扩展的共享库libcustomer.so(所以其他人隐式使用扩展的共享库)
  3. 通过-loldcustomer将liboldcustomer.so链接到我的扩展libcustomer.so中
  4. 将任何不是额外实现的方法直接转发给旧的“liboldcustomer.so”

我认为它不会那样工作(名称被编译成.so,不是吗?)。 但是替代方案是什么?

对于#4:是否有一般的方法来做到这一点,或者我是否必须编写一个名为旧的方法并转发呼叫(如何?)?

因为原始的libcustomer.so(= liboldcustomer.so)可能会不时发生变化,所有这些东西都应该动态地工作。

出于安全原因,我们的系统没有LD_PRELOAD(否则我会接受:()。

考虑扩展validation检查和一些更好的NPE处理。

在此先感谢您的帮助!

编辑:

我正在实现我的扩展,如答案中所示,但我目前有一个未处理的案例:

如何从扩展库“代理”结构?

例如我有这个:

customer.h:

struct customer; 

customer.c:

 struct customer { int children:1; int age; struct house *house_config; }; 

现在,在我的customer-extension.c中,我正在编写customer.c的所有公共方法,但是如何“传递”结构?

非常感谢您的时间和帮助!

所以你有OldLib

 void func1(); int func2(); ... etc 

步骤4可能看起来像创建具有一些静态初始化的另一个库。

使用内容创建NewLib:

 void your_func1(); void (*old_func1_ptr)() = NULL; int (*old_func2_ptr)() = NULL; void func1() { // in case you don't have static initializers, implement lazy loading if(!old_func1_ptr) { void* lib = dlopen("OldLibFileName.so", RTLD_NOW); old_func1_ptr = dlsym(lib, "func1"); } old_func1_ptr(); } int func2() { return old_func2_ptr(); } // gcc extension, static initializer - will be called on .so's load // If this is not supported, then you should call this function // manually after loading the NewLib.so in your program. // If the user of OldLib.so is not _your_ program, // then implement lazy-loading in func1, func2 etc. - check function pointers for being NULL // and do the dlopen/dlsym calls there. __attribute__((constructor)) void static_global_init() { // use dlfcn.h void* lib = dlopen("OldLibFileName.so", RTLD_NOW); old_func1_ptr = dlsym(lib, "func1"); ... } 

如果您对旧API有一些描述,则可以自动生成static_global_init和所有func_ptr 。 创建NewLib后,您当然可以替换OldLib。