參考: https://blog.csdn.net/weiwangchao_/article/details/16880401html
http://luajit.org/ext_c_api.htmlapi
http://www.javashuo.com/article/p-rxlxzfnu-bd.html數據結構
lua 調用 C,須要用到 lua 的 ffi 庫,它容許從純Lua代碼調用外部C函數,使用C數據結構,可是C的數據類型並不必定都能轉化成lua的數據類型。ide
#include <unistd.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <stdio.h>
#include <dirent.h>函數
struct rlimit rlmt;ui
char* get_size()
{
if (getrlimit(RLIMIT_CORE, &rlmt) == -1) {
return -1;
}
return (char*)rlmt.rlim_cur;lua
};spa
char* set_size(double CORE_SIZE)
{
rlmt.rlim_cur = (rlim_t)CORE_SIZE;
rlmt.rlim_max = (rlim_t)CORE_SIZE;.net
if (setrlimit(RLIMIT_CORE, &rlmt) == -1) {
return -1;
}code
return (char*)rlmt.rlim_cur;
};
int cd_chdir(const char *dirname)
{
int a=chdir(dirname);
return a;
};
【g++ 編譯一下,變成 *.so 文件 】
下面爲 Makefile 文件, 在目錄下 make 能直接生成 *.so 文件 ,修改裏面的 *.so *.o 文件
## Linux/BSD
LDFLAGS += -shared
CFLAGS ?= -g -O -Wall
override CFLAGS += -fpic
#CC = gcc
RM = rm -f
COPY = cp
all: my_corefile.so
my_corefile.o: my_corefile.c
my_corefile.so: my_corefile.o
$(CC) $(LDFLAGS) $^ -o $@
clean:
$(RM) *.so *.o
lua 文件
local ffi = require 'ffi'
--local ffi_string = ffi.string
--local ffi_new = ffi.new
--local C = ffi.C
ffi.cdef[[
int get_size();
int set_size(long CORE_SIZE);
int cd_chdir(const char *dirname);
]]
set_get_core = ffi.load('/home/chentao/c_test/c_lua/qq/mycorefile/my_corefile.so')--直接導入絕對路徑
local a = set_get_core.get_size()
print(a)
local b = set_get_core.set_size(524280)
print(b)
print("hass set")
local a = set_get_core.get_size()
print(a)
print(os.getenv("PWD"))
print(" cd ",set_get_core.cd_chdir("/home"))
導入路徑爲 絕對路徑