3

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.
Thanks!


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.

//GPS.h
#include "GPSWrapper.h"
STATUS_Code GPSInitialize(void);
//GPS.c
#include "GPS.h"
STATUS_Code GPSInitialize(void) {
  GPS_cCallback();
}
//GPSWrapper.h
#import <Foundation/Foundation.h>
@interface GPSWrapper: NSObject
- (void) testObjC;
@end
//GPSWrapper.m
#import "GPSWrapper.h"
static id refToSelf = nil;
@implementation GPSWrapper
  - (void) testObjC {
    // just an example of a ObjC method call
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSLog(documentsDirectory);
  }
@end

static void GPS_cCallback() {
  [refToSelf testObjC];
}
Community
  • 1
  • 1
setzuiro
  • 427
  • 5
  • 13
  • OSX and iOS audio programs are full of instructive examples: while a program in its entirety is written in Obj-C, the critical audio processing code has to be "streamlined" down to plain-C. Please, see the SO tag "core-audio". – user3078414 Jul 20 '16 at 19:57
  • This doesn't really make sense; C is 100% usable from ObjC. Yes, it's one-way: you can't #include an ObjC header in a file compiled as C, or make ObjC message sends, but it should be no problem at all to provide wrappers for your must-be-C functions in either an ObjC class or in C functions that are inside a file compiled as ObjC. Can you maybe provide a minimal demo of what you're doing and explain exactly how it fails? – jscs Jul 20 '16 at 20:25
  • You can call C methods from Objective-C, it is no big deal. Don't rename thing, just include the .c and .h files and go from there. You are over thinking it. – MoDJ Jul 20 '16 at 21:24
  • The problem isn't so much calling to C from ObjC, but more so having calling to ObjC in (.m) files from C methods in (.c) files. I updated my question with additional details and sample test code or what my expectations were. – setzuiro Jul 21 '16 at 15:01

1 Answers1

2

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."
#endif

#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;

@end

 //  StringCounter.m
 //  OCFromC

 #import "StringCounter.h"

 @implementation StringCounter

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

 @end

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"
#endif

#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 {

        doThatThing();
        // 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;
        doThatThingWithThisObject(scRef);
    }
    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.

jscs
  • 63,694
  • 13
  • 151
  • 195
  • That was a beautiful answer to my question. Slightly related question though, I noticed here we're returning size_t for byte size, but while playing around a I had to define return type of strings in objc as `const char *` to c (knowing that c strings are character arrays). Took me a while to figure this out, but how would I define other common data types in this scenario? – setzuiro Jul 26 '16 at 13:38
  • I picked `size_t` so that the C side doesn't have to get the definition of `NSUInteger`, which is the actual return type of `lengthOfBytesUsingEncoding:`. They're not strictly the same, but as a practical matter, (AFAIK) they are the same size on all platforms. For this whole project, it's important to note that any valid C you write is valid as ObjC. Therefore, in the crossover interface, you simply need to make sure that you're using standard C types. – jscs Jul 26 '16 at 16:46