使用Lua v5.1.3,注意代码中的路径。
mylib.c :
/**
* 创建新的VC DLL工程,空的;
* 加入头文件和lua51.lib;
* 加入本文件。
*
* m = assert(package.loadlib("mylib.dll", "luaopen_mylib"))
* m()
* = mylib.sin(2)
* 或:
* dofile("mylib.lua")
* = mylib.sin(2)
*
* 注意: 接收返回值的变量不能用mylib,否则导致冲突;
* 注意:必须定义LUA_LIB和LUA_BUILD_AS_DLL等宏定义。
*/
#define LUA_LIB
#define LUA_BUILD_AS_DLL
#include "lua.h"
#include "l_auxlib.h"
#include "lualib.h"
#include <math.h>
static int l_sin (lua_State *L) {
double d = luaL_checknumber(L, 1);
lua_pushnumber(L, sin(d));
return 1; /* number of results */
}
static const struct luaL_reg mylib [] = {
{"sin", l_sin},
{NULL, NULL} /* sentinel */
};
LUALIB_API int luaopen_mylib (lua_State *L) {
// luaL_openlib(L, "mylib", mylib, 0);
luaL_register(L, "mylib", mylib);
return 1;
}
|
mylib.lua :
assert(package.loadlib("C:\\lua\\mylib\\Release\\mylib.dll", "luaopen_mylib"))()
|
打开lua.exe,输入:
require("mylib.lua")
= mylib.sin(2)
|
也可这样编译,从etc/luavs.bat修改而来,mylib.bat:
@rem Script to build mylib.dll mylib.lib under "Visual Studio .NET Command Prompt".
@setlocal @set MYCOMPILE=cl /nologo /MD /O2 /W3 /c /D_CRT_SECURE_NO_DEPRECATE @set MYLINK=link /nologo @set MYMT=mt /nologo
%MYCOMPILE% mylib.c @rem %MYCOMPILE% /DLUA_BUILD_AS_DLL mylib.c %MYLINK% /DLL /out:mylib.dll mylib.obj lua51.lib del mylib.obj mylib.exp
|
阅读(1898) | 评论(1) | 转发(0) |