开发者

Extending an API in C in a flexible and unobtrusive way

开发者 https://www.devze.com 2023-04-01 09:16 出处:网络
I\'m trying to add some additional functionality to an API. However, I\'d like these additional function开发者_如何转开发s to be in an external library of mine and not mixed with the original library\

I'm trying to add some additional functionality to an API. However, I'd like these additional function开发者_如何转开发s to be in an external library of mine and not mixed with the original library's code.

The problem comes when I need to access static functions of the mentioned API from my functions. Of course I can't, so the only solution I see is either to copy these functions' code into my API or to make them non-static in the original API. Both are not too good options for me for obvious reasons.

More precisely:

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

Could you suggest which would be the most flexible way to handle this?

I'd like to point out that it's related to C only, not C++.


  1. Make the functions static.
  2. Create an extern struct with pointers to these functions. Declare it in a separate #include file, available to the extension, but not to the entire world.
  3. Use the struct in your extension.

Something like this:

// 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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号