Friday, October 09, 2009

Block/Closure Extension to C/Objective C/C++


I've been trying to force myself to get back into some Objective C/Cocoa development. I got a bit of an itch again after looking into the new OpenCL. If you don't want to read all about it it's basically a standard that Apple started and was able to get Intel, Nvidia and AMD on board and eventually submitted it to the Krhonos group for standardization. It basically allows you to write programs to take advantage of all the cores of cpus/gpus, similiar in what Nvidia was doing with Cuda. To ease development when working with OpenCL blocks/closures where also added as an addition to C.

I really wanted to play around with some of these but was hard pressed to find any good examples for both C and ObjC.

So here's a quick one in plain ol' C

void test1( void(^block)(char*) ) {


    block("Message from 'block'");


}



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


    test1(^(char *msg) { printf("Block Message: %s\n", msg); });


    return 0;

}



And in ObjC
- interface

#import <objc/Object.h>


typedef void(^Block)(char*);


@interface HelloWorld : Object {


}


- (void) displayBlockMessage: (Block)block;


@end




- implementation

#import "HelloWorld.h"


@implementation HelloWorld


- (void) displayBlockMessage: (Block)block {


block("<HelloWorld> block message");


}


@end



- main

#import "HelloWorld.h"


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


HelloWorld *helloWorld = [[HelloWorld alloc] init];


// inline block


[helloWorld displayBlockMessage: ^(char *msg) {


printf("%s\n", msg);


}];


// declared block


Block block = ^(char *msg) {


printf("-=%s=-", msg);


};


[helloWorld displayBlockMessage: block];


return 0;


}



One thing you'll notice is that the interface declares 'block (typedef void(^Block)(char *);' This is because you need a type for the 'displayBlockMessage' functions signature (unless there's some trick :) ). Another thing is that I'm inheriting from the base objc object type and not the Cocoa NSObject, it will work either way I was just playing around with also compiling it on Windows.

I'm still surprised that C is getting block/closures before Java. C++0x is also suppose to have their own implementation as well.

4 comments:

BlackTigerX said...

that is painful to look at, apparently Jobs is not on those design meetings :P

oh, and Java is dead :)

Justin Wilson said...

Yes, I think I may have made it a bit complex looking with the full implementation of the interface/object etc.

I created another post to compare just the block/closure syntax with that of C#'s anonymous method syntax here.

BlackTigerX said...

...and I'm sure you would be amused to know that I've been programming in Java lately

Justin Wilson said...

Lol! I thought it was dead

Java for work? or Java for play? What do you get to build?? details details!