Thursday, January 13, 2011

I'm Not Very "Objective"

Some time ago I was asked to implement a javascript interpreter for iOS,
 so some people could write javascript instead of Objective-C if they are
afraid of learning a new language. Of course we could build from ground
up with a parser generator such as Antlr, which I found to be very fascinating.
However given the deadline of a couple of weeks this is a little too challenging,
 thus I had been googling for a quick solution like crazy. Well, there were
indeed some open source libraries like SpiderMonkey, JSCocoa and JavascriptCore,
which I tried to port to iOS but I wasn't very successful in the end. Just as I was
about to throw in the white towel I came to a site which explained how
one can just expose the hidden JavascriptCore framework from Apple and use
them! The steps one has to take is roughly:
1. Include "dlfcn.h", which defines the dynamic library loading functions.
2. Since the libraries are loaded by default, we can simply use dlsym to get
    a pointer to the function of interest, like below:
    _JSEvaluateScript = dlsym(RTLD_DEFAULT, "JSEvaluateScript");

3. Include JSBase.h, JSContextRef.h, JSObjectRef.h, JSStringRef.h, JSStringRefCF.h, JSValueRef.h in the project.
And here is the video which shows the results from user input, function 1 and function 2: