ioscobjective-ccross-platform

Call objective-c method from C library


I have a cross platform library written in C (.a) to do cryptographic stuff.

I use it that way on Android

+------------------------+           +-----------------+
|      Android (Java)    |           |  Android (Java) |
+------------------------+           +-----------------+
   1.|              /|\               3.|           /|\
    \|/            4.|                 \|/         2.|
+------------------------------------------------------+
|                    myFramework.a (C)                 |
+------------------------------------------------------+

So the following function is called by Java, then call Java for something not related to the previous "context"

#ifdef __ANDROID__
#include "jni.h"

static JNIEnv *gEnv;
static jobject gObj;

int doStuff(char* aString) { /* have fun calling java */ }

#else

#include "oni.h" // objective c native interface ? :3

#endif

This function will use JNIEnv and jobject to access Java methods.

I have included the C library in the iOS project but can't find a way to call an objective-c method from the C library (part 2. and 3.)

How can I call an objective-c method from a C library?


Solution

  • You can absolutely call Objective-C methods from C functions. To do so, however, you will need to make sure that your C function has a reference to an Objective-C object of some kind. Your example above doesn't show that.

    So, you might write your function as:

    int doStuff(id ref, char* aString) {
      [ref objcMethod];
      ....
      return 0;
    }
    

    Or maybe you would store the ref in static storage in your library, so that it was available to all functions, without passing it explicitly. It really depends on your use-case. Remember that Classes are objects, too, in Objective-C; so if you need ref to be a class (for a static methods), that can work, too.

    There is a tangential topic. Sometimes, in Objective-C you want a direct reference to a method implementation so that you can invoke it directly. This is handy in tight loops, where performance is required. If this is your need, this blog post goes into the topic.