Help: writing ffi bindings to a C library

Bayley, Alistair
Wed, 21 May 2003 16:27:10 +0100

I want to write a set of bindings to Oracle's OCI library (a low-level C
library for doing stuff to the Oracle database). Before I get started, has
anyone done this already? (I don't think so, but I'd better ask.)

My goal is to start with a simple set of low-level bindings, and build this
up to higher-level database abstractions, and to hopefully port HaskellDB
(if it's possible).

But to start with I simply want to create a set of bindings for the OCI
functions and get them working. Trouble is, I have no idea how to start
writing a FFI binding. So far I've read:
 - Haskell 98 FFI Addendum (RC8) : a reference, but not a tutorial.
 - : incomplete
 - : is this
for writing C that calls Haskell functions?

Can anybody point me to a tutorial, or some illustrative examples? At the
moment I'm trying to avoid the various ffi tools, and just use the basic ffi
capabilities in GHC, so I can get an idea of how it all works. When I'm more
comfortable with ffi then I'll think about using the various tools to speed
things up.

I'm not sure how to treat structures used by the C library. For example, a
sample C program might have:

int main ()
	sword rc;
	OCIEnv *envhp = NULL;
	OCIServer *srvhp = NULL;
	OCIError *errhp = NULL;
	OCISvcCtx *svchp = NULL;
	OCISession *usrhp = NULL;
	OCIStmt *stmtp = NULL;

	rc = OCIEnvCreate(&envhp, OCI_DEFAULT, 0, 0, 0, 0, 0, 0);
	rc = OCIHandleAlloc(envhp, (dvoid**) &errhp, OCI_HTYPE_ERROR, 0, 0);
	rc = OCIHandleAlloc(envhp, (dvoid**) &srvhp, OCI_HTYPE_SERVER, 0,

How do I handle values of OCIEnv, OCIServer, etc? I think I'm supposed to
use Ptr, ForeignPtr, and Storable to reference them, but I don't see how to
combine these types/classes (ForeignPtr takes values of type Ptr a; how do I
construct a Ptr a? What type should "a" be?).

The information in this email and in any attachments is 
confidential and intended solely for the attention and use 
of the named addressee(s). This information may be 
subject to legal professional or other privilege or may 
otherwise be protected by work product immunity or other 
legal rules.  It must not be disclosed to any person without 
our authority.

If you are not the intended recipient, or a person 
responsible for delivering it to the intended recipient, you 
are not authorised to and must not disclose, copy, 
distribute, or retain this message or any part of it.