开发者

Best way for Lua script to call a C shared lib?

开发者 https://www.devze.com 2023-01-25 05:57 出处:网络
I come from more of a Python and CTYPES background...and am trying to work out the best way to call a standard C shared lib from Lua script.

I come from more of a Python and CTYPES background...and am trying to work out the best way to call a standard C shared lib from Lua script.

I have heard of "Alien" (http://alien.luaforge.net/), but am not sure how current it is? Meaning it is updated regulary?

For example, I know that thier is an SQLite Lua library but let's say I wanted to call the SQLite shared lib that is created when I compile SQLIte?

So for example: In my case the lib is in /usr/local/lib/libsqlite3.so

If I write a little dummy script just to see if it can load the lib

require "libsqlite3"

print "hello"

I get the following error:

debian@debian:~/Desktop/SQLite Test$ lua sqlite_test.lua
lua: error loading module 'libsqlite3' from file '/usr/local/lib/lua/5.2/libsqlite3.so':
    /usr/local/lib/lua/5.2/libsqlite3.so: undefined symbol: luaopen_libsqlite3
stack traceback:
    [C]: in ?
    [C]: in function 'require'
    sqlite_test.lua:1: in main chunk
    [C]: in ?
debian@debia开发者_高级运维n:~/Desktop/SQLite Test$ 

Does this mean that Lua cannot call shared libs "out the box" and that I HAVE TO use something like Alien?

I know I can also code the shared lib in such a way that it includes the Lua header files and I can make "Lua functions"...I was just hoping I could call shared libs that are "standard" on the box.

And help or advise would be greatly appreciated ;-)

Thanks

Lynton


Lua cannot call C libraries out of the box. It does not ship with libffi, and as such doesn't work like ctypes.

Historically, lua is embedded into an application which in turn will add to the lua tables the needed functions and provide the lua stack manipulation to pass and return parameters.

Alien is a libffi adaptation and will work.


Like Yann said, Lua cannot call C libraries by default. The usual practice is to expose the wanted API by means of creating a binding library. There are several places, where you can look for existing library bindings for Lua, like the wiki, LuaRocks or LuaDist.

If no bindings exist, you may try to use Alien to bind straight to C libraries using libffi.

For your example - Sqlite3, there are at least 2 bindings:

  • generic SQL binding - LuaSql, provides binding to Sqlite3, MySQL, Oracle...
  • specialized binding - Lua-Sqlite3
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号