Hi all, after a rather long hiatus from Ocaml I’m looking at trying to make use of the language once again for fun little projects in my spare time. The other day I was thinking about trying to wrap some C++ code (but I’m using C for this test) in an Ocaml library, and I ran into a something that confuses me a bit.
In a nutshell, I can create a ctypes foreign function in the bin executable code, but creating a ctypes foreign function in the lib directory and naively adding the library to the bin executable fails.
Steps I take (which may miss something very essential…)
- dune init project cpptest
- Create lib/fib.ml, lib/fib.c, and lib/fib.h
lib/fib.ml content:
open Ctypes
open Foreign
let fib = foreign "fib" (int @-> returning int)
lib/fib.c content:
#include "fib.h"
int fib(int n)
{
if (n < 2) return 1;
else return fib(n - 1) + fib(n - 2);
}
lib/fib.h content:
#ifndef CPPTEST_FIB_H
#define CPPTEST_FIB_H
#ifdef __cplusplus
extern "C" {
#endif
int fib(int n);
#ifdef __cplusplus
}
#endif
#endif /* CPPTEST_FIB_H */
- Add libraries and foreign stubs to lib/dune
lib/dune
(library
(name cpptest)
(foreign_stubs (language c) (names fib))
(libraries ctypes ctypes-foreign))
- Update bin/main.ml and bin/dune
bin/main.ml
open Printf
open Cpptest
let () = printf "%d\n" (Fib.fib 20)
bin/dune
(executable
(public_name cpptest)
(name main)
(libraries cpptest))
- dune build is successful
- dune exec cpptest results in in a symbol lookup error
Fatal error: exception Dl.DL_error("_build/install/default/bin/cpptest: undefined symbol: fib")
- On the other hand, putting fib.c and fib.h in bin/, and add the foreign declaration of fib in main.ml works.
bin/main.ml
open Printf
open Ctypes
open Foreign
let fib = foreign "fib" (int @-> returning int)
let () = printf "%d\n" (fib 20)
bin/dune
(executable
(public_name cpptest)
(name main)
(foreign_stubs (language c) (names fib))
(libraries ctypes ctypes-foreign))
- dune build is successful (just like when trying the library version)
- dune exec cpptest calls the C fib() function successfully (in contrast to the library version)
10946
Any insights into what I am overlooking would be very welcome!