Skip to content

Instantly share code, notes, and snippets.

@amirrajan
Last active May 15, 2020 23:17
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save amirrajan/de9e40af5d48a52c646700699682d3b6 to your computer and use it in GitHub Desktop.
Calling objc from c.
#include <objc/objc.h>
#include <objc/runtime.h>
#include <objc/message.h>
#include <objc/objc-auto.h>
void hello_world()
{
/* Objective C
id le_string = [[NSString alloc] initWithCString: "hello world", NSUTF8StringEncoding];
unichar character = [le_string characterAtIndex: 0];
NSLog(@"%C", character);
*/
// id le_string = [[NSString alloc] initWithCString: "hello world", NSUTF8StringEncoding];
id nsstring = objc_getClass("NSString");
SEL alloc = sel_registerName("alloc");
int NSUTF8StringEncoding = 4;
SEL initWithCString = sel_registerName("initWithCString");
id allocated_memory_space_le_string = ((id (*)(id, SEL))objc_msgSend)(nsstring, alloc);
id le_string = ((id (*)(id, SEL, char (*), int))objc_msgSend)(allocated_memory_space_le_string,
initWithCString,
"hello world",
NSUTF8StringEncoding);
// unichar character = [le_string characterAtIndex: 0];
SEL characterAtIndex = sel_registerName("characterAtIndex");
u_char character = ((id (*)(id, SEL, int))objc_msgSend)(le_string, characterAtIndex, 0);
// NSLog(@"%C", character);
printf("%C", character);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment