Reputation: 47
I'm trying to call a method implemented in Obj-C from C code as follows:
// MainViewController.m
- (void)Test
{
[self outputLine:@"Called from MyCode.c"];
}
.
.
.
cFunc(id param);
.
.
.
// MyCode.c
void cFunc(id param)
{
[param Test]; // compilation error: Parse issue: Expected expression
}
I guess it happens since the MainViewController is not declared in MyCode.c, but when I #include the MainViewController.h I get tons of other errors that suggests I'm totally wrong... How should I handle it correctly?
TIA
Upvotes: 0
Views: 275
Reputation: 471
Just change your myCode.c to myCode.m :P
Don't be afraid to put C code in an Objective-C file.
Upvotes: 0
Reputation: 1168
Check: using objc_msgSend to call a Objective C function with named arguments
void cFunc(id param) {
objc_msgSend(param, sel_getUid("Test"));
}
But, as per the link above, this is dangerous for a few reasons, if your arguments don't fit in registers (i.e. floats, structs, blah blah).
The accepted way of doing this is to cast objc_msgSend:
void cFunc(id param) {
// Now let's pretend that you want to send someFloat to your method
void (*objc_msgSendTyped)(id self, SEL _cmd, float bar) = (void*)objc_msgSend;
float someFloat = 42.f;
objc_msgSendTyped(param, sel_getUid("Test"), someFloat);
}
Upvotes: 0
Reputation:
You should compile the MyCode.c
file as Objective-C. Objective-C is a superset of C, but it's not true the other way around. You can't have Objective-C code interspersed with your "pure C" code if you are intending to compile it as C.
Upvotes: 4