void registerHandler(lua_State* state, function_type f) { if (state) { util::ScopedSavedStack save(state); lua_pushlightuserdata(state, this); if (class_userdata::newmetatable<function_type>(state))//register error handler destructor to Lua state { lua_pushcclosure(state, &error_handler_cleanner, 0); lua_setfield(state, -2, "__gc"); lua_setfield(state, -1, "__index"); void* ptr = lua_newuserdata(state, sizeof(function_type));//dummy data for gc call if (!ptr) { throw std::runtime_error("critical error. maybe failed memory allocation"); }//critical error function_type* funptr = new(ptr) function_type(); if (!funptr) { throw std::runtime_error("critical error. maybe failed memory allocation"); }//critical error class_userdata::setmetatable<function_type>(state); lua_settable(state, LUA_REGISTRYINDEX); *funptr = f; } else { function_type* funptr = getFunctionPointer(state); if (funptr) { *funptr = f; } } } }
function_type getHandler(lua_State* state) { function_type* funptr = getFunctionPointer(state); if (funptr) { return *funptr; } return function_type(); }
TEST(libjitTest, FunctionRunTest) { void* ptr = getFunctionPointer(ExistentFile, ExistentFunction); ASSERT_NE(ptr, (void*)NULL); typedef int (*fptr)(int, int); fptr function = (fptr) ptr; ASSERT_NE(function, (void*)NULL); // function = two int's sum EXPECT_EQ(function(0, 0), 0); EXPECT_EQ(function(1, 5), 6); EXPECT_EQ(function(5, -9), -4); }
void unregisterHandler(lua_State* state) { if (state) { function_type* funptr = getFunctionPointer(state); if (funptr) { *funptr = function_type(); } } }
jint JNI_GetCreatedJavaVMs(JavaVM **vmBuf, jsize bufLen, jsize *nVMs) { static const struct mach_header *header = 0; if (!header) { header = loadFramework("/System/Library/Frameworks/JavaVM.framework/JavaVM"); } static jint(*functionPointer)(JavaVM **, jsize, jsize *) = 0; if (!functionPointer) { functionPointer = getFunctionPointer(header, "_JNI_GetCreatedJavaVMs"); } return functionPointer(vmBuf, bufLen, nVMs); }
TEST(libjitTest, NonExistentFileTest) { EXPECT_EQ(getFunctionPointer(NonExistentFile, ""), (void*)NULL); }
TEST(libjitTest, ExistentFunctionTest) { EXPECT_NE(getFunctionPointer(ExistentFile, ExistentFunction), (void*)NULL); }