Lua 언어 는 자신 이 작성 한 C DLL 을 어떻게 호출 합 니까?

Lua           C DLL  

#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
#include <windows.h>

static int MyLuaDLL_HelloWorld(lua_State* L)
{
     MessageBox(NULL,"Hello","World",MB_OK);
     return 0;
}
static int MyLuaDLL_average(lua_State *L)
{
    
     int n = lua_gettop(L);
     double sum = 0;
     int i;
    
     for (i = 1; i <= n; i++)
     {
        
         sum += lua_tonumber(L, i);
     }
    
     lua_pushnumber(L, sum / n);
    
     lua_pushnumber(L, sum);
    
     return 2;
}

static const luaL_reg MyLuaDLLFunctions [] =
{
     {"HelloWorld",MyLuaDLL_HelloWorld},
     {"average",MyLuaDLL_average},
     {NULL, NULL}
};

int __cdecl __declspec(dllexport) luaopen_MyLuaDLL(lua_State* L)
{
     luaL_openlib(L, "MyLuaDLL", MyLuaDLLFunctions, 0);
     return 1;
}
 
-- lua code: --

local testlib = package.loadlib("Lua_Dll.dll","luaopen_MyLuaDLL");   --  DLL       
print (testlib) 
if(testlib)then
    testlib();  --  DLL     
else
    -- Error
end

MyLuaDLL.HelloWorld();

a,b=MyLuaDLL.average(23,33,3344);
print("average:",a,"sum:",b);
--------------------------------------------
my.c  :

#include "stdafx.h"
#include <stdio.h>
#include "my.h"

static int pri(lua_State *L)
{ 
 MessageBox(NULL,"Hello","this is a c program!",MB_OK);
 return 0;
}

static const struct luaL_Reg mylib[]={
 {"pri",pri},
 {NULL,NULL}
};

__declspec(dllexport) int luaopen_mylib (lua_State* L)
{
 luaL_register(L,"mylib",mylib);
 return 1;
}

my.h  :

#include "lua.h" 
#include "lualib.h"
#include "lauxlib.h"
#pragma   comment(lib,"lua5.1.lib")

test.lua  :

local a=package.loadlib("my.dll","luaopen_mylib");

a()
mylib.pri()

좋은 웹페이지 즐겨찾기