We will write the client in the main hello/ subdirectory. The main program will be written in C. File hello.c is as follows:
#include <stdio.h> #include "Hello_World.h" int main(int argc, char** argv) { Hello_World h = Hello_World__create(); char* msg = Hello_World_getMsg(h); printf("%s\n", msg); Hello_World_deleteRef(h); free(msg); }
This code creates the Hello_World object, calls the getMsg() method, prints the ubiquitous saying, decrements the reference count for the object, and frees the message string.
There are a few details worth noting here. The C bindings generate function names by combining packages, classes, and method names with underscores (e.g. Hello_World_getMsg(). Whenever you see double underscores in Babel generated symbols, they indicate something built-in to (and sometimes specific to) the language binding. The _create() method is built-in to every instantiatable class defined in SIDL, triggering the creation of Babel internal data structures as well as the constructor of the actual object implementation.
To generate the C glue code necessary to call the library, we run the Babel tool again, this time specifying C as the target language:
% babel -client=C hello.sidlor simply
% babel -cC hello.sidl
The ``-cC'' flag, or its equivalent long-form ``-client=C'', tells the Babel code generator to create only the C stub calling code, not the entire library implementation. The library libhello.so already contains the necessary IOR, skeleton, and implementation object files. We compile the hello program using the following GNU Make Makefile:
.c.o: gcc -I$(HOME)/babel/include -Ilib -c $< include babel.make OBJS = hello.o ${STUBSRCS:.c=.o} hello: ${OBJS} gcc ${OBJS} -o $@ \ -Rlib -Llib -lhello \ -R$(HOME)/babel/lib -L$(HOME)/babel/lib -lsidl clean: ${RM} *.o hello
Note that the ``-R'' flags tell the dynamic library loader where to find the hello and sidl shared libraries. You could achieve the same behavior through environment variables such as LD_LIBRARY_PATH. On some machines and compilers (notably linux-gcc-3.0) the -R flag is no longer supported, so you will have to modify the appropriate environment variable to find the shared library.
Finally, we make the executable and run it:
% make hello
% ./hello
Hello World