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

参考: 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"))

导入路径为 绝对路径

相关文章
相关标签/搜索