libobjc: Calling a ObjC method from plain C?

176 Views Asked by At

I am currently experimenting with the V programming language and looked at a few fun things I wanted to try out. One of the things that I wondered was, if I could call Objective-C methods from plain C without compiling a single .m file.

Since Python can do it with pyobjc, I wonder if I could make it work in V?

Imagine the following, very crude code:

@implementation Foo

- (id) greet: (char*)me {
  printf("Hello %s!", me);
}

@end

Now, I know that with objc_sendMsg I can send messages - but how do I create the proper instance first?

1

There are 1 best solutions below

2
Scott Thompson On

It's going to look something like this:

Class fooClass = objc_lookUpClass("Foo");
id obj = class_createInstance(fooClass, 0);
SEL initSelector = sel_registerName("init");
((id (*)(id, SEL))objc_msgSend)(obj,initSelector);