是否可以从 OCaml 调用 C 函数并有效地传递一个巨大的数组?
我正在考虑在新应用程序中结合使用 OCaml 和 C 代码。 从 Ocaml 调用 C 代码似乎很简单:
external name : type = C-function-name
然而,反过来(从 C 调用 OCaml)似乎也更复杂:(
static void
call_ocaml_void (const char * name)
{ CAMLparam0 () ;
CAMLlocal1 (ostr) ;
ostr = caml_copy_string (name);
value * func = caml_named_value ("ocaml_puts") ;
if (func == NULL)
puts ("caml_named_value failed!") ;
else
caml_callback (*func, ostr) ;
CAMLreturn0 ;
} /* call_ocaml_void */
示例来自此 页面)
尤其是,它涉及复制。
谁能告诉我是否可以允许从两种语言访问数据结构? 因此,函数只能传递指向结构的指针,但两种语言都可以读取它。
目标是使用 OCaml 完成所有操作,然后以有效的方式将数据传递到 C 环境。
谢谢!
I'm considering the use of a combination between OCaml and C code in a new application. It seems that calling C code from Ocaml is simple:
external name : type = C-function-name
However, it seems also that in the other way around (calling OCaml from C) is more complicated:
static void
call_ocaml_void (const char * name)
{ CAMLparam0 () ;
CAMLlocal1 (ostr) ;
ostr = caml_copy_string (name);
value * func = caml_named_value ("ocaml_puts") ;
if (func == NULL)
puts ("caml_named_value failed!") ;
else
caml_callback (*func, ostr) ;
CAMLreturn0 ;
} /* call_ocaml_void */
(Example from this page)
And especially, it involves copying.
Could anyone tell me if it is possible to allow access to a data structure from both languages? So the functions could pass only pointers to the structure, but both languages can read it anyway.
The objective is to do all the operations with OCaml, and then pass the data to the C environment in an efficient way.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,您可以将任何 C malloced 值作为抽象类型传递给 ocaml。 它们有几个问题:
你还可以使用包含指向任何内容的指针的自定义块。 这也是一个基础值(如前一种情况),但您可以添加一些在自定义块被 GC 时调用的代码,这将负责释放 C 对象。
然后,对于整数/字符/浮点数组,您可以使用 biggaray 库“可以使用 alloc_bigarray 包装指向已分配的 C 或 Fortran 数组的指针 p 并将其作为大数组返回到 Caml
或 alloc_bigarray_dims 函数。 " 请参阅手册
Firstly you can pass any C malloced value to ocaml as an abstract type. Their are severall problem with this :
You can also use custom block containing a pointer to anything. This is also an bastract value (as in the previous case) but you can add some code to be called when the custom block is GCed and that will take care of freeing the C object.
Then for array of integer/char/float you have the biggaray library "A pointer p to an already-allocated C or Fortran array can be wrapped and returned to Caml as a big array using the alloc_bigarray
or alloc_bigarray_dims functions. " see the manual