Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] Accuracy of Gc.stat ()
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Kim Nguyen <nguyen@b...>
Subject: Re: [Caml-list] Accuracy of Gc.stat ()
Hi,

On Wed, 19 Nov 2003 18:52:10 +0100
Daniel Bünzli <daniel.buenzli@epfl.ch> wrote:

> 
> 3) Is it possible to know at runtime whether we are running native code 
> or interpreted bytecode ?
> 

There is actualy an (ugly) hack which seems to work, but it requires few lines of C codes :

--- prog.ml --

(* An external declaration, first C function is used when compiled to bytecode, 
    second when compiled to native code.
*)

external is_bytecode : unit -> bool = "is_bytecode_bytecode" "is_bytecode_native"

(* And now you can use it... *)
let _ = 
	if is_bytecode () 
	then 
	print_endline "Bytecode !!!"
	else
	print_endline "Native code !!!"

-----------

--- bytecode.c -----

#include <caml/mlvalues.h>

CAMLprim value is_bytecode_bytecode(value unit){
  return Val_true;
}
CAMLprim value is_bytecode_native(value unit){
  return Val_false;
}

-------------

Et voilà !

Linking native caml code with this C code isn't a big deal but, linking with
bytecode make you somehow loose the portability of the later. 
See the corresponding chapter in the Ocaml manual (Chapter 18).

$ gcc -c bytecode.c
$ ocamlc -make-runtime -o myruntime bytecode.o
$ ocamlc -o prog -use-runtime ./myruntime prog.ml
$ ocamlopt -o prog.opt bytecode.o prog.ml
$ ./prog
Bytecode !!!
$ ./prog.opt
Native code !!!

I wonder if there is a cleaner way to do this. Maybe there could be a flag like
 the Sys.interactive one. I'd like to know how "safe" is this code, the behavior 
of the compiler is only described for function with more than 5 arguments in 
the manual.


Cheers.

Kim Nguyen.