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插件的设置:






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


  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值