lua使用ffi调用c程序的函数

参考: https://blog.csdn.net/weiwangchao_/article/details/16880401

   http://luajit.org/ext_c_api.html

https://www.cnblogs.com/darkknightzh/p/5812763.html

lua 调用 C,需要用到 lua 的 ffi 库,它允许从纯Lua代码调用外部C函数,使用C数据结构,但是C的数据类型并不一定都能转化成lua的数据类型。

#include <unistd.h>

#include <sys/time.h>

#include <sys/resource.h>

#include <stdio.h>

#include <dirent.h>

struct rlimit rlmt;

char* get_size()

{

  if (getrlimit(RLIMIT_CORE, &rlmt) == -1) {

  return -1;

  }

  return (char*)rlmt.rlim_cur;

};

char* set_size(double CORE_SIZE)

{

  rlmt.rlim_cur = (rlim_t)CORE_SIZE;

  rlmt.rlim_max = (rlim_t)CORE_SIZE;

  if (setrlimit(RLIMIT_CORE, &rlmt) == -1) {

  return -1;

  }

  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"))

导入路径为 绝对路径