【问题标题】:Load and use symbols from shared library with ctypes in OCaml toploop在 OCaml toploop 中使用 ctypes 从共享库中加载和使用符号
【发布时间】:2017-06-05 14:52:28
【问题描述】:

我正在尝试使用来自 OCaml 的小型自包含 fortran 库中的函数。我可以用gfortran -shared mvndst.f -o sharedlib 编译库。调用 nm sharedlib 会显示符号列表,例如... T _mvndfn_

阅读 ctypes 教程示例 https://github.com/ocamllabs/ocaml-ctypes/wiki/ctypes-tutorial 后,我尝试做类似 let mvndfn = foreign "mvndfn" (ptr double @-> returning float) 的事情。未找到该符号。也许并不奇怪,因为我没有告诉它在哪里看 - 但我不知道怎么看。

这可以工作吗?如何告诉 toploop 寻找这个共享库?它是 Fortran 而不是 C 有关系吗?如果程序在 toploop 中工作,我如何最终编译和链接程序?

(这是在 OS X 上)

【问题讨论】:

    标签: ocaml ctypes


    【解决方案1】:

    Foreign.foreign 接受一个可选参数?from,它是一个Dl.library 类型的值(你可以看到它in the docs)。您可以使用Dl.dlopen 获得其中一个(动态加载是一个复杂的主题,但您经常需要[RTLD_LAZY])。

    这里是一个使用libpng的例子:

    # let libpng = Dl.dlopen ~flags:[Dl.RTLD_LAZY] ~filename:"/usr/lib/x86_64-linux-gnu/libpng16.so.16";;
    val libpng : Dl.library = <abstr>
    # open Foreign;;
    # open Ctypes_static;;
    # let f = foreign ~from:libpng "png_get_libpng_ver" (ptr void @-> returning (ptr char));;
    val f : unit Ctypes_static.ptr -> char Ctypes_static.ptr = <fun>
    # let p = f Ctypes.null;;
    val p : char Ctypes_static.ptr = (char*) 0x7f9d5220e64e
    # Ctypes.string_from_ptr ~length:6  p;;
    - : string = "1.6.26"
    

    【讨论】:

    • 你可以在函数类型中找到可选参数,只需在顶层输入Foreign.foreign;; :)
    猜你喜欢
    • 2019-02-10
    • 1970-01-01
    • 2015-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多