Browse thread
caml_copy_string
[
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: | Florent Monnier <monnier.florent@g...> |
| Subject: | Re: [Caml-list] caml_copy_string |
Le dimanche 22 août 2010 01:30:28, Jeffrey Barber a écrit :
> Is there a way to get a string from C to OCaml without the caml_copy_string
> function, or is there a version that doesn't copy the string?
an alternative method is to provide a string from ocaml to c then c fills this
buffer, then you can save allocations by reusing the same buffer, see:
ocamlopt -o test.opt main.ml main_stub.c
$ time ./test.opt 1
44 seconds elapsed
$ time ./test.opt 2
21 seconds elapsed
========================
#include <string.h>
#include <caml/mlvalues.h>
#include <caml/alloc.h>
#include <caml/fail.h>
static const char *str = "the walking camel";
static const int len = 18;
CAMLprim value ml_mystr1(value unit) {
return caml_copy_string(str);
}
CAMLprim value ml_mystr2(value ml_buf) {
int buf_len = caml_string_length(ml_buf);
if (len > buf_len) caml_failwith("buffer overflow");
memcpy(String_val(ml_buf), str, len);
return Val_int(len); /* len chars were written in the buffer */
}
========================
external mystr1: unit -> string = "ml_mystr1"
external mystr2: string -> int = "ml_mystr2" "noalloc"
let n = 1_000_000_000
let test1() =
for i = 1 to n do
let _ = mystr1 () in ()
done
let test2() =
let buf = String.create 100 in
for i = 1 to n do
let _ = mystr2 buf in ()
done
let () =
match Sys.argv.(1) with
| "1" -> test1()
| "2" -> test2()
| _ -> assert false
========================
--
Regards
Florent