从 C 头文件生成 Ocaml 绑定存根

发布于 2024-12-12 19:38:40 字数 158 浏览 2 评论 0原文

我有一个头文件,它为某个库声明了 C API,我想为此库创建一个 OCaml 绑定。我发现 camlidl 可以从 IDL 文件创建存根,但据我了解,没有从 *.h 文件到 IDL 文件的自动转换,所以现在我想知道是否有其他方法来生成存根来自 C 头文件的 OCaml 绑定?

I have a header file which declares a C API for some library and I would like to create an OCaml bindings for this lib. I found that camlidl can create stubs from an IDL file but as I understand there is no automatic conversion from a *.h file to IDL, so now I wonder if there is any other way to generate stubs for OCaml bindings from a C header file?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

謸气贵蔟 2024-12-19 19:38:40

C 头文件中没有足够的信息来编写另一种语言的绑定。在非常简单的情况下(例如,所有函数仅接受整数或浮点参数),这是可能的,但是一旦涉及指针,您就需要提供更多信息:函数是否会从指向的值读取、写入到它,还是两者兼而有之?接口必须允许空指针吗?这实际上是一个指向数组的指针吗?它的大小在哪里?这个 char* 是指向以零结尾的字符串的指针吗?

IDL 使用额外的注释扩展了 C 函数声明以涵盖所有这些要点。这就是 camlidl 在 IDL 上工作而不是直接在 C 标头上工作的原因。你不会发现任何明显减轻痛苦的事情。

还有另一种方法,即使用具有空扩展但提供额外类型信息的宏来随意注释您的 C 头文件,例如

int memmove(void ANN_OUT ANN_SIZE(n) ANN_NOT_NULL *dest,
            const void ANN_IN ANN_SIZE(n) ANN_NOT_NULL *src,
            size_t n);

此类注释不是标准化的,因此如果您走这条路,您将不得不编写自己的工具。 (如果你想解析 C,请查找 Cil。)我建议你这样做将 IDL 声明视为主要声明,并根据它们生成 C 头文件。

There is not enough information in a C header file to write bindings for another language. In very simple cases (for example, all functions take only integer or floating-point arguments), it's possible, but as soon as pointers get involved, you need to provide more information: will the function read from the pointed-to value, write to it, or both? Must the interface allow a null pointer? Is this in fact a pointer to an array, and where's the size? Is this char* a pointer to a zero-terminated string?

IDL expands C function declarations with extra annotations to cover all these points. That's why camlidl works on IDL and not directly on C headers. You won't find anything significantly less painful.

There's another approach, which is to liberally annotate your C headers with macros that have an empty expansion but provide extra type information, e.g.

int memmove(void ANN_OUT ANN_SIZE(n) ANN_NOT_NULL *dest,
            const void ANN_IN ANN_SIZE(n) ANN_NOT_NULL *src,
            size_t n);

Such annotations are not standardized, so if you go this route you'll have to write your own tools. (Look up Cil if you want to parse C.) I recommend that instead you treat the IDL declarations as primary, and generate the C header files from them.

说不完的你爱 2024-12-19 19:38:40

Swig 有帮助吗?

Would Swig be helpful?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文