Skip to Main Content
Mac OS X for Unix Geeks
book

Mac OS X for Unix Geeks

by Ernest E. Rothman, Brian Jepson
September 2002
Beginner to intermediate content levelBeginner to intermediate
216 pages
7h 43m
English
O'Reilly Media, Inc.
Content preview from Mac OS X for Unix Geeks

Dynamically Loading Libraries

You can turn answer.o into a bundle, which can be dynamically loaded using the commands shown in Example 5-6.

Example 5-6. Commands for converting answer.o into a bundle
cc -flat_namespace -bundle -undefined suppress \
  -o libanswer.bundle answer.o

You do not need to specify the bundle at link time. Instead, use the dyld functions NSCreateObjectFileImageFromFile and NSLinkModule to load the library. Then, you can use NSLookupSymbolInModule and NSAddressOfSymbol to access the symbols that the library exports. Example 5-7 loads libanswer.bundle and invokes the get_answer function. Example 5-7 is similar to Example 5-4, but many lines (shown in bold) have been added.

Example 5-7. Dynamically loading a bundle and invoking a function
/*
 * deep_thought_dyld.c: Obtain the answer to life, the universe,
 * and everything, and act startled when you actually hear it.
 */
#include <stdio.h>
#import <mach-o/dyld.h>

int main(  )
{
  int the_answer;
  int rc;                // Success or failure result value
  NSObjectFileImage img; // Represents the bundle's object file
  NSModule handle;       // Handle to the loaded bundle
  NSSymbol sym;          // Represents a symbol in the bundle
int (*get_answer) (void);  // Function pointer for get_answer

  /* Get an object file for the bundle. */
  rc = NSCreateObjectFileImageFromFile("libanswer.bundle", &img);
  if (rc != NSObjectFileImageSuccess) {
    fprintf(stderr, "Could not load libanswer.bundle.\n");
    exit(-1);
  }

  /* Get a handle for the bundle. */
  handle = NSLinkModule(img, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mac OS X For Unix Geeks, 4th Edition

Mac OS X For Unix Geeks, 4th Edition

Ernest E. Rothman, Rich Rosen, Brian Jepson
Mac OS X Hacks

Mac OS X Hacks

Kevin Hemenway, Rael Dornfest
Mac OS X in a Nutshell

Mac OS X in a Nutshell

Jason McIntosh, Chuck Toporek, Chris Stone

Publisher Resources

ISBN: 0596003560Errata Page