如何使用 NIF 与在调用之间保持状态的 C 代码进行交互(即,链表作为 NIF)
我想创建一个用 C 实现的链表数据结构。这个想法是创建一个链表 ListId
ll:new() -> listId.
,上面表示某种类型的“指针”,该指针将传递回可以运行的 C 代码作为列表中某种类型的句柄。我希望不必来回传递列表本身,因为我想象列表可能会变得非常非常大。一旦创建了链接列表,用户就会以明显的方式与其交互:
ll:add(ListId, Elt)
ll:add_after(ListId, Pos, Elt)
我想我会通过 Erlang 的 NIF 功能来做到这一点。现在,为了使其工作,C 端必须在多次调用 add、add_after 等中维护列表。
在直接 C 中,我将有一个用户与之交互的主函数,该函数将使程序保持活动状态,从而保持链表在用户与程序交互的整个生命周期中持续存在。据我了解,NIF 使用 C 代码,没有主函数。也就是说,对 NIF 的每次调用都是一次性完成的命题类型。
有人可以给我一些关于如何(假设合适)利用 NIF 与需要在多个调用之间保持状态的 C 代码进行交互的指示吗?我希望这是清楚的!
I wanted to create a linked-list data structure that was implemented in C. The idea was that one would create a linked list
ll:new() -> listId.
ListId, above, represents a "pointer" of some type that would get passed back to the C code which would function as some type of handle on the list. I was hoping not to have to pass the list itself back and forth since I imagined lists could get very, very large. Once the linked list was created, users would then interact with it in obvious ways:
ll:add(ListId, Elt)
ll:add_after(ListId, Pos, Elt)
I imagined I would do this via Erlang's NIF capabilities. Now, for this to work the C side has to maintain the list across multiple calls to add, add_after, etc.
In straight C, I would have a main function that a user interacts with that would keep the program alive thereby keeping the linked list persisted for the life of the user's interaction with the program. As I understand it, NIFs utilizes C code with no main function. That is, that each call to a NIF is a one-and-done type of proposition.
Can someone give me some pointers on how (assuming it is appropriate) one can utilize NIFs to interact with C code that needs keeps state across multiple calls? I hope that was clear!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
检查资源对象的文档。 NIF API 甚至允许您使用 erlang GC 来 GC 您创建的列表,以防创建列表的进程崩溃!
Check the documentation for resource objects. The NIF API even allows you to use the erlang GC to GC the lists you create should the process which has created it crash!
C 中的“静态”变量可以在调用之间保留值,但我强烈不推荐这种方式。如果你需要一些状态,最好看看 erlang 中的“ports”。
the 'static' variable in C can keep value between calls, but I would strongly dont recommend this way. If you need some state, it would be better to look at 'ports' in erlang.