Search code examples
c++functionsymbolsffiluajit

How to expose a function from C++ executable to LuaJIT


I am trying to load a Lua script into my c++ app and run it. I decided to use LuaJIT to harness its FFI library. But I have this weird problem where my Lua script cannot see the function symbols I defined in my C++ code and I get this error upon running my app:

undefined symbol: test_func_a

below is my C++ and Lua Code:

//C++//

#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <lua.hpp>

#ifdef __cplusplus
  extern "C" {
#endif

void test_func_a ( void ) {
  printf ( "hello\n" );
}

#ifdef __cplusplus
  }
#endif

int main ( int argc, char** argv ) {
  lua_State *lua = luaL_newstate();
  assert ( lua );
  luaL_openlibs ( lua );
  const int status = luaL_dostring ( lua, lua_script_content );

  if ( status )
    printf ( "Couldn't execute LUA code: %s\n", lua_tostring ( lua, -1 ));

  lua_close ( lua );

  return 0;

}

//Lua//

local ffi = require('ffi');

ffi.cdef[[
  void test_func_a (void);
]]

ffi.C.test_func_a()

by default gcc will export all symbols, how come luajit fails to see them?


Solution

  • use:

    extern "C" __declspec(dllexport) void test_func_a ( void ) {printf ("hello\n" );}