码迷,mamicode.com
首页 > 其他好文 > 详细

lua调用cpp的DLL

时间:2016-03-27 17:41:58      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:

首先新建一个cpp项目,命名为cppLibForLua,把lua的库引入,添加如下文件,编译成DLL

GameHelp.h

#ifdef GAME_HELP_API
#define API __declspec(dllexport)
#else
#define API __declspec(dllimport)
#endif

extern "C"
{
    API int fastPow(lua_State *L);
    API int  luaopen_MyLuaDLL(lua_State* L);
}

GameHelp.cpp

#define GAME_HELP_API
#include "GameHelp.h"

static int mi2[] = {
0x80000000,0x40000000,0x20000000,0x10000000,
0x08000000,0x04000000,0x02000000,0x01000000,
0x00800000,0x00400000,0x00200000,0x00100000,
0x00080000,0x00040000,0x00020000,0x00010000,
0x00008000,0x00004000,0x00002000,0x00001000,
0x00000800,0x00000400,0x00000200,0x00000100,
0x00000080,0x00000040,0x00000020,0x00000010,
0x00000008,0x00000004,0x00000002,0x00000001,
};

int fastPow(lua_State *L)
{
    double v_num = lua_tonumber(L, -2);//第一个参数
    int v_index = lua_tonumber(L, -1);//第二个参数
    double rst = 1.0;
    int neg = v_index & 0x80000000;
    v_index = v_index > 0 ? v_index : -v_index;
    int i;
    for (i = 0; i < 32; i++)
    {
        if (v_index & mi2[i])
        {
            rst = rst * rst * v_num;
        }
        else
        {
            rst = rst * rst;
        }
    }
    if (neg) rst = 1 / rst;

    lua_pushnumber(L, rst);
    return 1;
}

lua调用代码

local path = "cppLibForLua.dll" 
local fastPow = package.loadlib(path,"fastPow")
local rst = fastPow(2,5)
print("2^5 = "..rst)

任务完成~~~

lua调用cpp的DLL

标签:

原文地址:http://www.cnblogs.com/mizime/p/5326067.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!