Browse thread
Wrapping a callback to OCaml code from C
- Richard Jones
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
| Date: | -- (:) |
| From: | Richard Jones <rich@a...> |
| Subject: | Wrapping a callback to OCaml code from C |
Hi:
I'm currently making some OCaml bindings for some C code. The C code
which is causing me difficulty provides a callback interface.
The interface, in C, looks like:
typedef void callback_t (void *data, obj *o1, obj *o2);
void run (void *data, callback_t *callback);
When 'run' function is called, it will call the callback function
passed several times, passing 'data' as the first parameter. I want
to provide an equivalent function in OCaml.
My current best attempt is this, which uses the 'data' parameter to
hold the address of the OCaml closure:
static void
callback_wrapper (void *fvpv, obj *o1, obj *o2)
{
value *fvp = (value *) fvpv;
value fv = *fvp;
value o1v, o2v;
o1v = Val_obj (o1);
o2v = Val_obj (o2);
caml_callback2 (fv, o1v, o2v);
}
CAMLprim value
run_wrapper (value fv)
{
CAMLparam1 (fv);
value *fvp = &fv;
caml_register_global_root (fvp);
run (fvp, callback_wrapper);
caml_remove_global_root (fvp);
CAMLreturn (Val_unit);
}
I suspect that this code is wrong or GC-unsafe in some way. The
reason is that my program sometimes segfaults, and behaves differently
if I rewrite callback_wrapper in inconsequential ways.
Can someone tell me if I'm doing the right thing here?
Rich.
--
Richard Jones, CTO Merjis Ltd.
Merjis - web marketing and technology - http://merjis.com
Team Notepad - intranets and extranets for business - http://team-notepad.com