Dynlink error: invalid ELF header

Hi,
I’m trying to build a dynamic loader with the Dynlink module. Vg and Gg are opam libraries I want to load. Here is my code:

let dynload pkg =
  let path =  Findlib.package_directory pkg in
  let file =  Format.sprintf "%s/%s.cmxs" path pkg in
  try
   Dynlink.loadfile file
  with Dynlink.Error e -> print_endline (Dynlink.error_message e)

let main () =
  List.iter dynload ["gg" ; "vg"]

let _ = main ()

The problem is when I compile, it gives me the following errors:

error loading shared library: ~/.opam/4.05.0/lib/gg/gg.cma: invalid ELF header
error loading shared library: ~/.opam/4.05.0/lib/vg/vg.cma: invalid ELF header

I have done some research and I can’t find a way to fix it…
Is there a way to correct the problem other than recompiling each package ?

You seem to have a mismatch between native and bytecode archives.

Note that if your program is compiled in bytecode then it can only dynlink bytecode libraries (.cma). If your program is native, then it can only dynlink .cmxs archives.

Dynlink.adapt_filename may come in handy.

Best wishes,
Nicolás

Thanks for your quick reply!
Indeed, I copy the wrong part of the code. I added the adapt_filename as you suggest and it removes this error. It triggers another error but it’s not relevant with this topic.