Linux下Lua擴充so

來源:互聯網
上載者:User

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <errno.h>
#include <string.h>
 
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <limits.h>
 

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

/*  庫 open 函數的前置聲明   */
int luaopen_mylib(lua_State *L);

static int l_sin (lua_State *L) 
{
double d = luaL_checknumber(L, 1);
lua_pushnumber(L, sin(d));
//printf("ok now is  luahook!\n");
return 1; /* number of results */
}

static const luaL_Reg mylib[] =
{
{"lsin", l_sin},
{NULL, NULL} /* 必須以NULL結尾 */
};

 int luaopen_mylib(lua_State *L) 
{
  luaI_openlib(L, "mylib", mylib, 0);
return 1;
}

如果是.cpp檔案,在luaopen_mylib一定要加 extern "C", 否則匯出的函數會被重新命名,切記切記

編譯:gcc mylibs.c -fPIC -shared -o libmylib.so -llua

Makefile檔案

CXX =gcc

LIBNAME:=libmylib.so

HDRNAME:=mylibs.c

TARGETNAME:=mylibs

CNAME:=$(patsubst %,%.c,$(TARGETNAME))

ONAME:=$(patsubst %,%.o,$(TARGETNAME))

all:libmylib

libmylib: $(ONAME)

$(CXX) -g -shared -Wl,$(LIBNAME) \

-o $(LIBNAME) $(ONAME) -llua

%.o: %.c

$(CXX) -fPIC -c -Wall $(CNAME)clean:$(RM) *.o *.so

lua呼叫指令碼:

local one, two, three = package.loadlib("libmylib.so", "luaopen_mylib")()

print(mylib.lsin(10))

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.