setzuiro setzuiro - 1 year ago 91
iOS Question

How to communicate from pure C (.c files) SDK to IOS (obj-C, .m files) framework?

Preface: I have little experience with C integration in iOS, feel free to correct me on any misinterpretations I have about this.

I have a project that has a custom 2-tier "SDK" both written in C. The coreSDK makes method calls to the deviceSDK which communicates with the ios framework to execute hardware actions (ie. enable camera) or retrieve device information (ie. path to NSDocumentDirectory).

Unfortunately, due to the infrastructure, both SDK file extensions use (.h) and (.c) and cannot be changed to (.m) as some sources recommended. According to what I've read, I can create C-callbacks to the ObjC methods but that's only really viable for singletons, and the C-callback needs to be within the scope of the (.m) file.

I have tried creating a wrapper class in ObjC such that it has a C-callback from which the deviceSDK calls to, but when including the header(.h) for that (.m), the compiler seems to crash. If my understanding is correct, it's because the C-compiler cannot interpret the ObjC language contained in the (.m).

I believe theoretically is possible to write iOS apps in pure C with ObjC runtime, but ideally would rather not go down that route as what I've seen is absurdly complicated.

An example workflow

  1. ViewController.m method calls to coreSDK method (.c)

  2. coreSDK method calls to deviceSDK method (.c)

  3. deviceSDK needs to retrieve (for example) NSDocumentDirectory (or enable camera)

How can I achieve this?

Code examples would be most comprehensive and appreciated.


These are some(not all) references I've already looked into...

Edit: 2016-07-21

To clarify the issue, I'm having trouble making calls from C methods in (.c) files to ObjC methods in (.m) files, or figuring out an alternative means to retrieve information such as (for example) NSDocumentsDirectory in ObjC (.m files) and passing back to C in (.c) files.

Example Code: Of course it's incorrect but it's along the lines of my expectations or what I'm hoping to achieve.

#include "GPSWrapper.h"
STATUS_Code GPSInitialize(void);

#include "GPS.h"
STATUS_Code GPSInitialize(void) {

#import <Foundation/Foundation.h>
@interface GPSWrapper: NSObject
- (void) testObjC;

#import "GPSWrapper.h"
static id refToSelf = nil;
@implementation GPSWrapper
- (void) testObjC {
// just an example of a ObjC method call
NSString *documentsDirectory = [paths objectAtIndex:0];

static void GPS_cCallback() {
[refToSelf testObjC];

Answer Source

This line #include "GPSWrapper.h" in your example is the problem. You can't include a header that has ObjC syntax in a file that's being compiled as C. Any interface to the ObjC side that's being included in your C code needs to be broken out into its own header that contains only valid C. Here's a demo of what you need:

First, header and implementation file for the C-only stuff.

//  CUtils.h
//  OCFromC

#ifndef CUtils_h
#define CUtils_h

#include <stdio.h>

void doThatThingYouDo();

void doThatThingWithThisObject(const void * objRef);

#endif /* CUtils_h */

//  CUtils.c
//  OCFromC

// Proof that this is being compiled without ObjC
#ifdef __OBJC__
#error "Compile this as C, please."

#include "CUtils.h"
#include "StringCounterCInterface.h"

void doThatThingYouDo()
    printf("%zu\n", numBytesInUTF32("Calliope"));

void doThatThingWithThisObject(const void * objRef)
    size_t len = numBytesInUTF32WithRef(objRef, "Calliope");
    printf("%zu\n", len);

Note that second function; if you need to, you can pass around an object reference in C land, as long as it's cloaked in a void *. There's also some casting that needs to be done for memory management. More on that below.

This is the exciting ObjC class we'll be using:

//  StringCounter.h
//  OCFromC

#import <Foundation/Foundation.h>

@interface StringCounter : NSObject

- (size_t)lengthOfBytesInUTF32:(const char *)s;


 //  StringCounter.m
 //  OCFromC

 #import "StringCounter.h"

 @implementation StringCounter

 - (size_t)lengthOfBytesInUTF32:(const char *)s
     NSString * string = [NSString stringWithUTF8String:s];
     return [string lengthOfBytesUsingEncoding:NSUTF32StringEncoding];


Now, this is the important part. This is a header file that declares C functions. The header itself contains no ObjC, so it can be included in CUtils.c as you saw above.

//  StringCounterCInterface.h
//  OCFromC

#ifndef StringCounterCInterface_h
#define StringCounterCInterface_h

// Get size_t definition
#import <stddef.h>

size_t numBytesInUTF32(const char * s);
size_t numBytesInUTF32WithRef(const void * scRef, const char *s);

#endif /* StringCounterCInterface_h */

This is the connection point. Its implementation file is compiled as ObjC, and it contains the definitions of those functions just declared. This file imports the interface of StringCounter, and so the functions can use methods from that class:

//  StringCounterCInterface.m
//  OCFromC

#ifndef __OBJC__
#error "Must compile as ObjC"

#import "StringCounterCInterface.h"
#import "StringCounter.h"

size_t numBytesInUTF32(const char * s)
    StringCounter * sc = [StringCounter new];
    // Or, use some "default" object in static storage here
    return [sc lengthOfBytesInUTF32:s];

size_t numBytesInUTF32WithRef(const void * objRef, const char * s)
    StringCounter * sc = (__bridge_transfer StringCounter *)objRef;
    return [sc lengthOfBytesInUTF32:s];

Now, in main or wherever you like you can exercise those functions from CUtils:

//  main.m
//  OCFromC

#import <Foundation/Foundation.h>
#import "StringCounter.h"
#import "CUtils.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {

        // Create an object reference
        StringCounter * sc = [StringCounter new];
        // Tell ARC that I know this is dangerous, trust me,
        // pass this reference along.
        const void * scRef = (__bridge_retained void *)sc;
    return 0;

The bridging cast, along with its counterpart in StringCounterCInterface.m, lets you move an ObjC object through areas where ARC cannot go. It bumps the object's retain count before it is hidden in the void *, so that it will not be accidentally deallocated before you can __bridge_transfer it back to ObjC land.

One final note: If you are going to be passing object references around in C a lot, you might consider doing typedef void * StringCounterRef; and changing the signatures of everything appropriately.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download