2011-08-31 35 views
1

我正在嘗試向API添加一些附加功能。但是,我希望這些附加功能位於我的外部庫中,而不是與原始庫的代碼混合使用。以靈活且不顯眼的方式在C中擴展API

問題來了,當我需要從我的函數訪問所提到的API的靜態函數。當然,我不能,所以我看到的唯一解決方案是將這些函數的代碼複製到我的API中,或者使它們在原始API中是非靜態的。由於顯而易見的原因,這兩個選項對我來說都不是太好。

更確切地說:

original_api.c 
    void some_function() -> uses some_helper_function() 
    static some_helper_function() 

my_api_extension.c 
    void some_extended_function() -> needs to use some_helper_function from original_api.c, but can't 

你可以建議這將是處理這個最靈活的方式?

我想指出,它只與C相關,而不是C++。

+0

它變得非常的混亂。我看到的唯一可行的解​​決方案是將我的代碼寫入一個頭文件中,我將其包含在原始庫中...... –

回答

1
  1. 使功能靜態。
  2. 使用指向這些函數的指針創建一個extern struct。聲明它在一個單獨的#include文件中,可用於擴展,但不適用於整個世界。
  3. 在您的擴展中使用struct

事情是這樣的:

// in the private header 
typedef struct 
{ 
    void (*p_myfunc1)(int); 
    int (*p_myfunc2)(void); 
} privateAPI_t; 
extern privateAPI_t privateAPI; 

// in the library 
static void myfunc1(int); 
static int myfunc2(void); 

privateAPI_t privateAPI = { myfunc1, myfunc2 }; 

// in the extension 
#include <privateAPI.h> 
... 
privateAPI.p_myfunc1(privateAPI.p_myfunc2()); 
+0

這真是太棒了! –

+0

所有編譯好的,但我得到函數的空指針。 'privateAPI_t privateAPI = {myfunc1,myfunc2};'在SO庫中,而'privateAPI.p_myfunc1(privateAPI.p_myfunc2());'在使用這個庫的應用程序中。任何想法該怎麼辦? –

+0

我不確定有什麼問題,但是我通過做了一個明確的動態初始化來修復它。也就是說,我不是在使用外部變量,而是在庫中使用init函數來在運行時執行此操作。重要的是它的工作。謝謝你! –