- C 70%
- OCaml 30%
objc #
Shared Objective-C / CoreFoundation FFI glue for OCaml bindings to Apple frameworks.
Framework bindings such as vz and fsevents need the same C helpers over
and over. A stub that calls into Objective-C has to keep an object alive while
OCaml holds it. It turns paths into NSURLs and reports each NSError as an
exception. Get one of those a little wrong and you leak memory or free
something twice, so the bindings share a single copy of the helpers, kept
here.
You mostly use it from C. The header objc.h is installed with dune's
install_c_headers, so a stub library that depends on objc can include it.
On the OCaml side there is only a small module that makes the boxed handles
abstract.
Installation #
Install with opam:
$ opam install objc
If opam cannot find the package, it may not yet be released in the public
opam-repository. Add the overlay repository, then install it:
$ opam repo add samoht https://tangled.org/gazagnaire.org/opam-overlay.git
$ opam update
$ opam install objc
What it provides #
Handles #
objc_wrap(void *) stores a CoreFoundation or Objective-C pointer in a custom
block and returns it to OCaml as an Objc.handle. When the GC finalizes the
block, the pointer gets a CFRelease. From C, objc_handle(v, ctx) gives you
the pointer back, or raises if the handle has already been finalized. OCaml
code only ever sees an abstract type, so it has no way to mistake the pointer
for an integer or to free it itself.
Errors #
The trap here is caml_failwith. It leaves the stub with a longjmp, which
skips the end of any @autoreleasepool block it was called from, and every
autoreleased temporary in that pool leaks. objc_raise_error avoids it by
pulling the message out of the NSError in a pool of its own, draining that
pool, and raising afterwards. If your stub already has a pool open, call
objc_error_msg to copy the message into your own buffer, leave the pool,
and call caml_failwith once it has drained.
Paths #
objc_file_url makes an NSURL from a C path and checks the result for nil.
It reports failure through an error buffer instead of raising, for the same
reason as above: the caller's pool has to drain first.
Using it #
Add objc to the stub library's dependencies:
(library
(name myframework)
(libraries objc)
(foreign_stubs (language c) (names myframework_stubs) ...))
Then include the header and wrap each object you return with objc_wrap:
#include "objc.h"
CAMLprim value caml_myframework_open(value v_path) {
CAMLparam1(v_path);
CAMLlocal1(result);
char errbuf[512];
errbuf[0] = '\0';
@autoreleasepool {
NSURL *url = objc_file_url(String_val(v_path), errbuf, sizeof errbuf);
if (url) {
/* ... build a framework object, then: */
result = objc_wrap((__bridge void *)obj);
}
}
if (errbuf[0]) caml_failwith(errbuf);
CAMLreturn(result);
}
The helpers only do something on macOS. Elsewhere they raise Failure, which
lets libraries that depend on them build on other platforms too.
License #
ISC. See LICENSE.md.