gpt4 book ai didi

c - OCaml - 编译使用 Ctypes 的 OCaml 和 C 代码

转载 作者:太空宇宙 更新时间:2023-11-03 23:24:27 25 4
gpt4 key购买 nike

我正在尝试学习如何使用 Ctypes 库直接从 OCaml 代码调用 C 中的例程。

我有一个包含两个文件的基本示例:hello.mlhello.c

hello.ml 看起来像这样:

open Ctypes
open Foreign

let hello =
foreign "hello" (float @ -> returning void)
;;

let () =
hello 3.15
;;

hello.c 看起来像这样:

#include <stdio.h>

void hello(double x)
{
if ( x > 0)
printf("hello!\n");
}

如何将这两个文件编译成一个可执行文件?

手动编译/链接代码的过程对我来说很可怕,我也不是很理解。我通常使用 Makefile 模板来编译我的代码,因为那真的很容易。

最佳答案

这是我在 OS X 上使用的示例。

在 simple.c 中

int adder(int a, int b)
{
return a + b;
}

在 simple.ml 中

open Ctypes
open Foreign
let adder_ = foreign
"adder" (int @-> int @-> returning int)

let () =
print_endline (string_of_int (adder_ 1 2))

那我做

clang -shared simple.c -o simple.so 
ocamlfind ocamlopt -package ctypes.foreign -cclib simple.so -linkpkg simple.ml -o Test
./Test

这应该会在终端上打印出 3。

关于c - OCaml - 编译使用 Ctypes 的 OCaml 和 C 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30534246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com