问题
My iOS application can use an optional external 3rd party library.
I thought of using this answer (Weak Linking - check if a class exists and use that class) and detect if the class exists before executing code specific to this library.
However, I found out that this external library is not written as Objective-C classes, but rather as C STRUTS and functions.
Is there a similar technique that would allow me to check if a C Strut or function exists? Or some better alternative to see if this library is present at runtime?
回答1:
struct
s are compile-time artifacts. They tell the compiler how to lay out a region of memory. Once that is done, struct
s become unnecessary. Unlike Objective-C classes which have metadata, structs
have no runtime presence. That is why it is not possible to detect them at runtime.
You can check if a dynamic library is present by calling dlopen, and passing its path:
void *hdl = dlopen(path_to_dl, RTLD_LAZY | RTLD_LOCAL);
if (hdl == NULL) {
// The library failed to load
char *err = dlerror(); // Get the error message
} else {
dlclose(hdl);
}
If dlopen
returns NULL
, the library cannot be loaded. You can get additional info by calling dlerror. You need to call dlclose after you are done.
回答2:
AFAIK a classical C function has to exist. It is statically bound during the linking process and it is not, like Objective-C mehtods, dynamically bound on runtime.
So when the code compiles AND links without errors or warnings, then you should be fine.
The same for structs.
来源:https://stackoverflow.com/questions/23041757/objective-c-check-if-structs-is-defined