Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ctypes and pointers to string arrays

Tags:

ocaml

I have a C function with the following signature:

void init(int* argc, char** argv[]);

I want to call this function from my OCaml code using Ctypes, but I can't figure a proper way to pass Sys.argv to it.

like image 867
Antoine Avatar asked Mar 22 '14 19:03

Antoine


1 Answers

This should make the trick:

module OArray = Array

open Ctypes;;
open Foreign;;

let init = 
  foreign "init" (ptr int @-> ptr string @-> returning void)

let init a =
  let argc = allocate int (OArray.length a) in 
  let argv = Array.of_list string (OArray.to_list a) in
  init argc (Array.start argv)

 let () = init Sys.argv

Note we need to keep a handle on OCaml's Array module because Ctypes overrides it, this will change in 0.3 see this report.

like image 158
Daniel Bünzli Avatar answered Nov 04 '22 01:11

Daniel Bünzli