Objective-C Check if Structs is defined

故事扮演 提交于 2019-12-13 04:24:43

问题


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:


structs are compile-time artifacts. They tell the compiler how to lay out a region of memory. Once that is done, structs 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!