Hacker News new | past | comments | ask | show | jobs | submit login
Design Issues for Foreign Function Interfaces (2004) (archive.org)
43 points by metagame 49 days ago | hide | past | favorite | 5 comments



Previous summary of this article, from a thread with otherwise no activity and with an author that no longer posts on HN, said more elegantly than I could dream of saying: https://news.ycombinator.com/item?id=1047559


The author is still active, here. The author is not really a lisper, just a normal polyglot, who happens to like lisp.

Beware that the standard libffi was written for Visual Basic. Which has one of the easiest FFI's. Did I write that? Forgot.


I was talking about mahmud, actually, the user who summed up your article.

Thanks for the article!


Very interesting article!

Unfortunately, it doesn't mention Lua, which in my opinion has one of the most elegant C APIs that I have seen. It is entirely stack based, which means you only need to work with primitive types, such as numbers, C strings and user provided opaque pointers. As a consequence, you never have to care about memory management because Lua doesn't even let you access the actual Lua objects.

You want to create a table (= Lua's dictionary/array hybrid) and set a field "foo" to 5? lua_newtable() creates a new table and pushes it onto the stack. Then you push "foo" with lua_pushstring() and 5 with lua_pushnumber(). Finally you call lua_settable(), which pops the key and value from the stack, checks if the top of the stack contains a table, and if yes, sets the given field to the given value. The actual table structure is never exposed!

This kind of stack manipulation might seem unusual and a bit unweildy, but what you get is safety. If you mess up the stack or perform illegal operations, Lua will call an error handler, but the VM should never crash. The stack API can be seen as the fundamental layer upon which people can create nice abstractions for their host language of choice. Examples are "sol2" for C++ (https://github.com/ThePhD/sol2) or "lupa" for Python (https://github.com/scoder/lupa)

The public API is contained in "lua.h": https://github.com/lua/lua/blob/master/lua.h. "lauxlib.h" offers some useful helper functions: https://github.com/lua/lua/blob/master/lauxlib.h

For comparison, this is Python's "Limited" C API: https://docs.python.org/3/c-api/stable.html#stable

If you want to learn more about Lua's C API, have a look at section 4 in https://www.lua.org/manual/5.4/manual.html


As a side note, LuaJIT is not only one of the fastest JIT compilers, it also offers a great FFI library for Lua.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: