calling c functions from lua script

2.3k views Asked by At

I found some references on this but I was not able to make them work. I have a Debian box with mysql and mysql-proxy. I am intercepting the SQL queries with the LUA script.

function read_query(packet)
        if packet:byte() ~= proxy.COM_QUERY then
                print("error read (COM_QUERY)")
        end
    local query = packet:sub(2)
    print ("query : " .. query )
           //Transformation here
    return proxy.PROXY_SEND_QUERY
end

I want to parse and process the query so I can rewrite it with some c functions I already have developed. I am trying to find the way to call this fucntions but the only way I have found asumes that the c MAIN function starts the LUA registering process.

Is there any way to make the LUA script call the function in a compiled C file?

Any example of how should I make (LUA) and receive (C) the call?

2

There are 2 answers

2
Mali On BEST ANSWER

Extract from lua.org

When we say that Lua can call C functions, this does not mean that Lua can call any C function.(There are packages that allow Lua to call any C function, but they are neither portable nor robust.) ... ... for a C function to be called from Lua, we must register it, that is, we must give its address to Lua in an appropriate way.

You should have a look here

0
Oliver On

SWIG is a good option to generate bindings for you: www.swig.org. You create a .i file in which load your C headers, and SWIG generates all the binding code for you. You then compile the generated code, link it to your C library and Lua library, and in your script you put require 'yourCLibrary', you can do what you want. Very practical, and your wrapper can be used to access yourCLibrary from other languages like Python and C#.