Objective-C Check if Structs is defined - objective-c

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?

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.

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.

Related

Is there a conventional URI scheme for referencing code in a library?

Is there a standard or conventional URI scheme, like file: or http: for referencing objects in a dynamic library?
For example, if I were to represent a function in a library in the form of a unique string that can be used to look up that function (by whatever reflective means), how might I do that?
Specifically I'm developing this in Objective-C, and I assume different languages/platforms will have different representations (I know .NET has its own), but I'm curious about this in a more general sense.
No, the name of the symbol is derived from its name in your code. In windows you will assuming C or C++
HMODULE module=LoadLibrary( [path to your dll] );
//If the exported name is foo.
Function foo=(Function)GetProcAddress(module,"foo");
//Call function
foo();
FreeLibrary(module);
The exported name is compiler-dependent.
Acually such a naming scheme is quite useless. In C++ you can use something like (Note that you will have one FunctionCaller per function prototype)
FunctionCaller("your-dll.dll/foo")();
Where the constructor of FunctionCaller loads the library, calls foo and frees the library. However it is not good because:
it may happen that the return value points to a resource inside the library and then will become useless
loading libraries and perform function look-up is slow relative to calling the function found
What you do is
Load the library
Load functions that you will need
Use your functions
Free the library
Here you would need to refer to more than one symbol at a time which would require a more complex scheme than uri.
EDIT: If you want to the convenience of calling functions like that you could have a surviving FunctionCaller object that keeps all loaded modules and contains a map from function name to address for each loaded library.

Categories provide dynamic loading?

I am looking at this page about C++ differences from Objective C and it states this:
The dynamic nature of Objective C allows existing classes to be extended at runtime. Objective C allows you to define categories, related sets of extensions to objects you've already created. For example, in converting a text-based app into a graphics app, the code your objects needed to draw themselves could be compiled as a category and loaded at run-time only when needed. This saves memory and allows you to leave your original objects unmodified.
Now I am familiar with Categories and have used them, but I do not see how they lead to dynamic loading. If you import a Category file, is it not compiled along with the class it extends, taking up memory whenever you use that class, whether you use the Category methods or not?
You can load a bundle/plugin/framework at runtime. This is the dynamic nature of Objective-c that the quote references. It is not specific to Categories.
However, if the (compiled) code you load includes a Category on an existing Class, the extensions will work just as if they had been there all along. Ie a Class is not 'Frozen' at compile time, and loading a bundle/plugin/framework is one way to add new methods to an existing class at runtime.
This makes it relatively easy to implement a plugin architecture, or load code only when needed to make app startup time faster/keep memory footprint down, compared to some other C based compiled languages.
If you link with a static library containing a category, the linker will copy all of the category code into your executable file. If you link with a shared library, the shared library's entire code segment gets mapped into your process's address space, but it's paged in lazily, so you might not actually read all of the category code off of the disk unless you use it all.
But I think that's not really what the page is talking about.
Link-time libraries
First, let's talk about libraries that you tell the linker to link your app with.
Consider NSString. The NSString class is defined in the Foundation framework, which is a framework full of general-purpose classes useful in programs that have GUIs and in programs that don't have GUIs. So the NSString class as defined in Foundation doesn't include any code for drawing a string into a graphics context, because that code would (usually) be useless in a non-GUI app.
The AppKit framework (on OS X) manages a GUI. It's useful in a GUI to be able to draw strings to a graphics context, so AppKit contains a category on NSString that adds methods for drawing a string, like drawAtPoint:withAttributes:. UIKit (on iOS) does the same thing (but the methods are a little bit different).
So if you write a program on the OS X and use Foundation but don't use AppKit, your process won't load the AppKit NSString category and you won't pay the price for all of those graphics methods on NSString.
For a shared library like AppKit, the price is pretty trivial on modern hardware.
Now, you could do the same thing with your own libraries, which you might make static. Let's say you make a “TwitterModel” library for talking to Twitter. It's full of classes that model the things you find on Twitter, like accounts and tweets. But you don't include code for managing a GUI to display tweets.
Instead, you make another library, “TwitterGUI”, that (in addition to defining yet more classes) uses categories to add methods to the model classes in your “TwitterModel” library.
If you write a program that links to both TwitterGUI and TwitterModel, the executable file will contain all of the Objective-C code from both libraries. But if you write a command-line only program (no GUI) and only link it with TwitterModel, that program won't contain any of the GUI-related code. Oh, the savings!
Run-time libraries
Now let's consider shared libraries that you don't tell the linker to link your app with.
You can dynamically load new code into your process at runtime, using an API like dlopen or -[NSBundle load]. If the library contains categories, those categories will be added to the classes in your running program.
So, you could make your app optionally use a shared library if it exists on the user's system when he runs your app, by trying to load the library programmatically. If you succeed, you can call any category methods that you know the library defines. (And of course you can use the classes that the library provides, if any.) If you fail to load the library, you carefully avoid calling any of those category methods from the library.
Typically, though, we use a dynamic loading API to load a plugin, and the plugin provides some class that subclasses a base class, or conforms to a protocol, that we've defined specifically for plugins to implement. We just need to get the name of that class, and then we create an instance of it and send it the messages that we defined in our base class or protocol.

Can I create an Objective-C class at run time from a text file?

I want to create an Objective C class at runtime from a file. So for example I have an objective c application, I want to then point it at a text file (or an .h .m pair, whatever works) and then have the application parse the text file and create the class at runtime (Class no object). Of course I would write the parser and all of that stuff I just want to know if its possible. I read these two articles:
http://www.mikeash.com/pyblog/friday-qa-2010-11-6-creating-classes-at-runtime-in-objective-c.html
http://www.mikeash.com/pyblog/friday-qa-2010-11-19-creating-classes-at-runtime-for-fun-and-profit.html
Which shows how to make an objective C class at runtime, but its being done using C functions which were defined at compile time. If I can find a way to do the same thing using strings to define the functions that would be perfect, because then I don't have to define them at compile time.
That's what called reflective programming. I guess there's no code evaluation support for Obj-C since it's not a scripting language, so the reflection concept for Obj-C is quietly limited. Plus, at run-time the compiler already translate the code into Obj-C clang code and it's a very time-consuming job just to reverse-translate the bytecode and recompile it again
For Obj-C reflection you can refer to these answers
Build a class :
Create objective-c class instance by name?
Implement a method :
Objective-C, how can i hook up a method in another class
Change class for an object :
Objective-C: How to change the class of an object at runtime?
Sure. Totally possible.
I would suggest starting with the Objective-C support in this as it includes a full-on Objective-C parser and code generator.
see my github project cocoa-interprreter it does part of what you want.
it takes a text file and compiles it at runtime .. and then runs the resulting executable using NSTask. It would be quite easy to change it so the binary is loaded into the own process using NSBundle
https://github.com/Daij-Djan/cocoa-interpreter

Is there a way to get a class by name?

In Objective-C, is there a way to get a class and send messages to it when you have the name of the class as a string? For example, is there a function func where func(#"NSString") == [NSString class]?
The reason that I want to know this is I am building a dynamic linker library for a language I am working on, and I want it to have an interface to Objective-C libraries.
Yes — two, in fact. If you have a Foundation-type framework (e.g. from Cocoa, Cocoa Touch or GNUstep), you can use the NSClassFromString() function, which is precisely the same as your func. If you do not want to depend on a framework, there's a similar runtime function, objc_getClass(), that takes a const char* and returns the named class (or nil if none is found).
You can use NSClassFromString(NSString className) to get the class object from its name.
Hope this helps!

Why do we still need a .lib stub file when we've got the actual .dll implementation?

i'm wondering why linkers can not do their job simply by consulting the information in the actual .dll files that got the actual implementation code ? i mean why linkers still need .lib files to do implicit linking ?
are not the export and relative address tables enough for such linking ?
is there anyway by which one can do implicit linking using only the .dll without the .lib stub/proxy files ?
i thought the windows executable loader would simply do LoadLibrary/LoadLibraryEx calls on behalf of the program (hence the name implicit linking) which is the main difference to explicit linking. if that is true then doing it explicitly without .lib should indicate that it is doable without it implicitly, right ? or i'm just saying non sense?
I can think of a a few reasons.
Using .lib files mean you can build for a different version of a DLL than you have on your system, provided you just have the correct SDK installed.
Compilers & linkers need to support cross-platform compilations - You might be building for a 64-bit target on a 32-bit platform and vice-versa and not have the correct architecture DLL present.
.lib files enable you to "hide" certain parts of your implementation - you could have private exports that do not show up in the .lib but are discoverable via GetProcAddress. You can also do ordinal exports in which case they don't have a friendly name exported, but would have a friendly name in the .lib.
Native DLL's do not have strong names, so it may be possible to pick up the wrong version of the DLL.
And most importantly, this technology was designed in the 1980's. If it were designed today, it'd probably be closer to what you describe - for instance, .NET you just need to reference the target assembly and you have everything you need to use it.
I don't know of any way to do implicit linking solely with the DLL - A quick search revealed several tools, but I haven't used any of them.
In this case, I would create a separate source file with the functions you need to use, and dynamically load the DLL and bind them as needed. For example:
// using global variables and no-error handling for brevity.
HINSTANCE theDll = NULL;
typedef void (__stdcall * FooPtr)();
FooPtr pfnFoo = NULL;
INIT_ONCE initOnce;
BOOL CALLBACK BindDLL(PINIT_ONCE initOnce, PVOID parameter, PVOID context)
{
theDll = LoadLibrary();
pfnfoo = GetProcAddress(dll, "Foo");
return TRUE;
}
// Export for foo
void Foo()
{
// Use one-time init for thread-safe lazy initialization
InitOnceExecuteOnce(initOnce, BinDll, NULL, NULL)
pfnFoo();
}