[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Embed ObjC in an API library?
From: |
Pascal Bourguignon |
Subject: |
Re: Embed ObjC in an API library? |
Date: |
Mon, 26 May 2003 20:07:24 +0200 |
Helge Hess writes:
> Kaelin Colclasure wrote:
> > Is it possible to implement a set of functions in Objective C, and then
> > wrap them with a plain-old C interface and package them as a shared
> > library?
>
> Yes. You actually only need to wrap them to make it more convenient for
> the C-developer. You can call any Objective-C method/class in ANSI-C by
> using the Objective-C runtime, eg:
>
> #include <objc/objc.h>
>
> objc_msg_lookup(myObject, sel_get_uid("doIt:"))
> (myObject, myArg);
Well, Kaelin asked for functions, not for objects and methods. When
you declare a function in Objective-C, you get exactly the function in
C, because Objective-C is a strict superset of C. There's no name
mangling like in C++. So you can write C function in an Objective-C
source (even inside @implementation/@end, this has nothing to do with
any name scoping), and call them from C (or even from C++ if
encapsulating the #include of the header inside extern "C"{...} (or
extern "Objective-C"{...} if the compiler accepts it)).
--------------<c-interface-to-module.h>------------
// Objective-C header
#ifndef c_interface_to_module_h
#define c_interface_to_module_h
extern void* module_func0(void)
extern int module_func1(void* ref,int arg);
extern int module_func2(void* ref);
extern int module_func3(int arg);
#endif
--------------<module.m>---------------------------
// Objective-C source
#include <SomeClass.h>
void* objc_module_func0(void)
{
return([[SomeClass alloc] init]);
}
int objc_module_func1(void* ref,int arg)
{
return([[(SomeClass*)ref method1:arg]]);
}
int objc_module_func2(void* ref);
{
return([[(SomeClass*)ref method2]]);
}
int objc_module_func3(int arg);
{
return(expr(arg));
}
--------------<client.c>---------------------------
#include <c-inteface-to-module.h>
void fun(void){
{
void* ref=moudle_func0();
module_func1(ref,module_func3());
module_func2(ref);
}
-------------------------------------------
Note that if what you want to encapsulate is message passing, doing it
in an Objective-C source allow you to use the [object message:arg]
notation instead of calling the low level API. That API should be of
use only for dynamic gluing. For example if you want to write stuff
like that:
char* action=compute_or_input_some_method_selector();
id sender=find_some_object();
id target=compute_some_object(sender);
imp method=objc_msg_lookup(target,sel_get_uid(action));
method(target,sender);
--
__Pascal_Bourguignon__ http://www.informatimago.com/
----------------------------------------------------------------------
Do not adjust your mind, there is a fault in reality.