1
votes

UPDATED: Problem solved. The dll must not be statically linking to lua, otherwise it crashes with a multiple Lua VMs detected exception. The code blow actually works fine, just leave it here in case someone got this problem too.

And wireshark uses lua5.2 because there's a "lua52.dll" in it's folder.


I'm writing wireshark plugin, some algorithm in C is difficult to implement in Lua, so I try to use these algorithm through dll.

Most examples online use the old version of Lua, which use luaL_register in the dll code. The luaL_register is replaced by lua_newtable/luaL_setfuncs in newer version, but I didn't find any working example online.

Here's what I tried :

#include <stdio.h>
#include <string.h>
#include "lua.hpp"

#include <windows.h>

extern "C" {
    static int add(lua_State* L)
    {
        MessageBox(0, "", "", 0);
        double op1 = luaL_checknumber(L,1);
        double op2 = luaL_checknumber(L,2);
        lua_pushnumber(L,op1 + op2);
        return 1;
    }

    static luaL_Reg mylibs[] = { 
        {"add", add},
        {0, 0} 
    }; 
    __declspec(dllexport)
    int luaopen_mylib(lua_State* L) 
    {
        lua_newtable(L);
        luaL_setfuncs(L, mylibs, 0);
        lua_setglobal(L, "mylib");

        return 1;
    }
}

and the lua code:

require "mylib" -- <----------crashes
-- local mylib = package.loadlib("mylib.dll","luaopen_mylib");  

print (mylib) 
if(mylib)then
    --mylib();
else
    -- Error
end

local b=mylib.add(11,33);
print("sum:", b);

The lua code crashes at first line. How to fix it?

Another question, how to verify which version of Lua is wireshark using? Calling print(_VERSION) in wireshark's lua console, it shows nothing.

1
If you've found a solution, please post it as an answer. - Colonel Thirty Two
You also corrupt your Lua stack. You should either remove the lua_setglobal call, or add a lua_pushvalue(L, -1) right before the lua_setglobal call, or change the return 1 after the lua_setglobal call to return 0. The first option is recommended, but you'd have to adapt your Lua code slightly (i.e. use local mylib = require "mylib"). - siffiejoe

1 Answers

0
votes

The crash occurs when statically linking to lua.lib, I guess there is already a lua VM in lua.lib, so use dynamic linking and the problem is gone.