lua入门之三:lua调用c/c++库(动态链接形式)

lua入门之三:lua调用c/c++库(动态链接方式)

dll通过函数luaL_openlib导出,然后lua使用package.loadlib导入库函数,基本就是这么个过程,下面上代码来说明一切。


#include "stdafx.h"


#ifdef __cplusplus
extern "C"{
#endif

#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"

#ifdef __cplusplus
}
#endif

#include <math.h>

#pragma comment(lib, "lua51.lib")


static int math_abs(lua_State *L)
{
	lua_pushnumber(L, abs((int)luaL_checknumber(L, 1)));

	return 1;
}

static int math_cos(lua_State *L)
{

	lua_pushnumber(L, cos((double)luaL_checknumber(L, 1)));

	return 1;

}

static int math_sin(lua_State *L)
{

	lua_pushnumber(L, sin((double)luaL_checknumber(L, 1)));


	return 1;
}

static const luaL_reg mathlib[] = {
	{ "abs", math_abs },
	{ "cos", math_cos },
	{ "sin", math_sin },
	{ NULL, NULL }
};


static int ShowMessage(lua_State * L)
{
	lua_pushnumber(L, 1000);
	printf("show message and push 1000 \n");
	return -1;
}


#ifdef _WIN32
extern "C" __declspec(dllexport) int luaopen_luadlllib(lua_State* L)
{
#else
extern "C"  int luaopen_luadlllib(lua_State* L)
{

#endif // _WIN32

	//MessageBox(NULL, TEXT("Register C++ Functions..."), NULL, MB_OK);

	luaL_openlib(L, "DY_MATH", mathlib,0);
	return 1;
}


--region loadlib.lua
	--Date
	--此文件由[BabeLua]插件自动生成

   --(package.loadlib("./../Debug/libforlua", "luaopen_luadlllib"))()
    --(package.loadlib("./../Debug/libforlua.dll", "luaopen_luadlllib"))()
    local libpath="./../Debug/libforlua.dll"
    local loadlibfunc=package.loadlib(libpath,"luaopen_luadlllib")
    loadlibfunc()

	function COS(a)
	print("called COS in lua script")
	return DY_MATH.cos(a)
	end


	function SIN(a)
	print("called SIN in lua script")
	return DY_MATH.sin(a)
	end


	function SHOWMESSAGE()
	showmessage()
	end

   

	print(COS(60*3.1415926/180))
    
    print("enter a number:") 
    a = io.read("*number") 

	--endregion


babelua插件的设置:


lua入门之三:lua调用c/c++库(动态链接形式)




示例工程的下载地址:http://download.csdn.net/detail/x356982611/7401781