Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] dynamically loading C functions
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Fabrice Le Fessant <fabrice.le_fessant@i...>
Subject: Re: [Caml-list] dynamically loading C functions

I've updated the dlopen ocaml port:
http://pauillac.inria.fr/~lefessan/src/dlopen/

It now works on 4 systems: x86, alpha, sparc and PPC.

It can use either printf formats or type combinators to specify
returned functions types. 

Type combinators must be use if you want to pass structs to C
functions (encoded by tuples in Caml), or get side-effects.

For example, it test.c defines:

struct tt {
  char field1;
  int  field2;
  char field3;
  double field4;
};

int set_tuple(struct tt* t)
{
  printf("%c - %d - %c - %f\n", t->field1, t->field2, t->field3, t->field4);
  t->field2 = 24;
  return 0;
}

You can use the following code:

# open Dlopen;; 
# let dll = dlopen "./test.so"  [RTLD_NOW];;
val dll : Dlopen.dll = <abstr>

# let struct_t =  record4_t (char_t, mutable_t int_t, char_t, float_t);;
val struct_t : (char * int ref * char * float) Dlopen.meta = <abstr>

# let set_tuple = dlsym_t dll "set_tuple" (
    star_t (mutable_t struct_t) @-> int_t);;
val set_tuple : (char * int ref * char * float) ref option -> int = <fun>

# let x =ref 1;;
val x : int ref = {contents=1}
# let y = ref ('a',x,'b',2.0);;
val y : (char * int ref * char * float) ref =
  {contents='a', {contents=1}, 'b', 2}

# set_tuple (Some y);;
a - 1 - b - 2.000000
- : int = 0

# x,y;;
- : int ref * (char * int ref * char * float) ref =
{contents=24}, {contents='a', {contents=24}, 'b', 2}

where both the references x and y capture the side-effect of the
function on the record (note that sharing is not preserved, ie in the
final result, 
   {contents=24}, {contents='a', {contents=24}, 'b', 2}
       ^                                ^
       ^-------------- != --------------^

Be careful to exactly encode the C arguments format in the Caml type
combinators (in particular, pointers are encoded by star_t as in the
example).

Regards,

- Fabrice
-------------------
To unsubscribe, mail caml-list-request@inria.fr.  Archives: http://caml.inria.fr