Decaf Sux
Decaf Sux

Reputation: 377

How to initialize api function pointers from a dynamic library in a C-API

I'm explicitly loading a c-API dynamic library (dll/so), where it is not possible to link symbols with a lib-file. So I use GetProcAddress and dlsym to find the apropriate functions.

The problem I have is due to the static declaration of "foo" and "baz" I have to use GetProcAddress/dlsym for every implementation file that includes this header.

The behaviour I want is that I only want to lookup the symbols once for the process.

Do I have to declare them all as "extern" then have a own set of function pointers in the project that I then set with GetProcAddress/dlsym?

What is the recommended way to fix it?

Example API header:

#ifdef _WIN32
#define API_IMPORT __declspec(dllimport)
#define API_EXPORT __declspec(dllexport)
#elif defined(__GNUC__)
#define API_EXPORT __attribute__((visibility("default")))
#define API_IMPORT
#else
#error Unsupported for now
#endif

#if LIB_COMPILING
#define API_DECL API_EXPORT
#else
#define API_DECL API_IMPORT
#endif

#ifdef __cplusplus
extern "C" {
#endif

API_DECL int ifoo(int bar);
API_DECL void ibaz(int qux);
typedef int (* PFN_FOO_PROC)(int);
typedef void (* PFN_BAZ_PROC)(int);
static PFN_FOO_PROC foo = 0;
static PFN_BAZ_PROC baz = 0;

#ifdef __cplusplus
}
#endif

"ifoo" and "ibaz" contains the actual implemenations in a c-file for the dynamic library.

So in this example to load symbols for linux:

        foo = (PFN_FOO_PROC) dlsym(handle, "ifoo");
        baz = (PFN_BAZ_PROC) dlsym(handle, "ibaz");

Thanks for any help

Upvotes: 0

Views: 153

Answers (1)

catnip
catnip

Reputation: 25388

The whole idea behind delay loading is that you don't have to use LoadLibrary / GetProcAddress. Instead, if (say) foo is a function in your delay loaded DLL you can simply say if (foo) before calling it to see if it's actually available.

I know less about Linux and macOS, but I do know that macOS has 'weak linking' which operates in a similar way. I don't know what Linux does, sorry, but I imagine it offers something similar.

Upvotes: 2

Related Questions