天天看點

c/c++混編,導出接口給lua調用lua注冊檔案 lnetReg.c編寫lua dll動态庫編寫lua lib靜态庫

最主要是為了使用c++11的裡面的一些東西,但這c11的東西又不能直接被lua調用,必須使用c還做 媒人
  • lua注冊檔案 lnetRegc
  • 編寫lua dll動态庫
  • 編寫lua lib靜态庫

lua注冊檔案 lnetReg.c

#include <lua.h>
#include <lauxlib.h>
#include <stdbool.h>

#define LUA_API_EXPORT __declspec(dllexport) 

extern bool Connect(const char* _ip, int _port); //在C檔案中不需要 "C",實作在gameNet.cpp中
static int
lconnect(lua_State *L) {
    size_t sz = 0;
    const char* ip = luaL_checklstring(L, 1, &sz);
    int port = luaL_checkinteger(L, 2);
    bool ret = Connect(ip, port);
    lua_pushboolean(L, ret);
    return 1;
}

LUA_API_EXPORT int
luaopen_network(lua_State *L) {
    luaL_checkversion(L);
    luaL_Reg l[] = {
        { "connect", lconnect },
        { NULL, NULL },
    };
    //luaL_newlib(L, l);
    lua_newtable(L);
    luaL_openlib(L, "network", l, 0);
    return 1;
}

在gameNet.cpp檔案中
extern "C" {
    bool Connect(const char* _ip, int _port)
    {
        return CGameNet::GetInstance()->Connect(_ip, _port);
    }
}           

然後gameNet.cpp 和 gameNet.h 就可以正常使用c++11的東西來寫,上面作為一個接口提供個 c 編譯

編寫lua dll動态庫

編譯選項:

1. 配置屬性-正常-目标檔案擴充名 改成 .dll
2. 配置屬性-正常-配置類型 改為 動态庫
           
LUA_API_EXPORT int //LUA_API_EXPORT __declspec(dllexport) 導出動态庫接口
luaopen_sproto_core(lua_State *L) { //lua中require "sproto_core"
#ifdef luaL_checkversion
    luaL_checkversion(L);
#endif
    luaL_Reg l[] = {
        { "newproto", lnewproto },
        { NULL, NULL },
    };
    luaL_newlib(L,l);           

lua中

local core = require “sproto_core” 
core.newproto(bin)           

編寫lua lib靜态庫

1. 配置屬性-正常-目标檔案擴充名 改成 .lib
2. 配置屬性-正常-配置類型 改為 靜态庫
           

在建立luastate的地方聲明

extern "C" {
    int luaopen_srp(lua_State *L);
}

lua_State* L = engine->getLuaStack()->getLuaState();
luaopen_srp(L); //注冊進lua中

LUA_API_EXPORT int
luaopen_srp(lua_State *L) {
    luaL_checkversion(L);
    luaL_Reg l[] = {
        { "create_verifier", lcreate_verifier },
        { NULL, NULL },
    };
    //luaL_newlib(L, l);
    lua_newtable(L);
    luaL_openlib(L, "srp", l, 0); //lua中require "srp"   
    return 1;
}           

lua中

local srp = require(“srp”) 
local private_key, public_key = srp.create_client_key()           

PS: 如果該庫中引用到xxx.lib,在需要在引用到這個srp.lib的工程中引入xxx.lib,否則報連結錯誤2019

a

繼續閱讀