繁体   English   中英

如何将字符串从 C++ 传递给 OCaml

[英]How to pass string to OCaml from C++

我在谷歌上没有找到任何关于此的内容,所以我正在回答我自己的问题:

如何将字符串从 C++ 传递给 OCaml?

给定 C++ 代码,我如何调用 OCaml 代码并传递该字符串?

也适用于 C,只需更改编译指令:

say_something.ml:

let say_something string = String.concat "" ["OCaml says: "; string]

let () = Callback.register "say_something" say_something

say_something.cc:

#include <stdio.h>
#include <string.h>
#include <caml/mlvalues.h>
#include <caml/callback.h>
#include <caml/alloc.h>


char *say_something(const char *s)
{
  static const value *say_something_closure = NULL;
  if (say_something_closure == NULL) {
    say_something_closure = caml_named_value("say_something");
    if (say_something_closure == NULL) {
      std::exit(1);
    }
  }

  value str = caml_alloc_initialized_string(strlen(s), s);
  /* We copy the C string returned by String_val to the C heap
     so that it remains valid after garbage collection. */
  return strdup(String_val(caml_callback(*say_something_closure, str)));
}

主.cc:

#include <stdio.h>
#include <caml/callback.h>

extern char* say_something(const char* s);

int main(int argc, char ** argv)
{
  char* result;

  /* Initialize OCaml code */
  caml_startup(argv);
  /* Do some computation */
  result = say_something("hello world\n");
  printf("%s", result);
  return 0;
}

如何构建:

ocamlopt -output-obj -o s.o say_something.ml
g++ -o hello_world -I $(ocamlopt -where) \
    main.cc say_something.cc s.o $(ocamlopt -where)/libasmrun.a -ldl

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM