【5.lua调用c】

1.先看lua文件
main.lua

function test ()
    print("------test----")
    package.cpath = "./?.so"
    local test = require "test"
    local sum = test.add(2, 3)
    print(sum)
    print("------end")
end
test()
~           

2.c文件
lua-test.c

#include  "/usr/local/src/lua-5.3.0/src/lua.h"
#include  "/usr/local/src/lua-5.3.0/src/lualib.h"
#include  "/usr/local/src/lua-5.3.0/src/lauxlib.h"
#include  "test.h"

static int l_add(lua_State* L){
    int x = luaL_checknumber(L, 1);
    int y = luaL_checknumber(L, 2);
    int sum = test_add(x, y);
    lua_pushinteger(L, sum);
    return 1;
}


int luaopen_test(lua_State* L)
{
    luaL_checkversion(L);
    luaL_Reg l[] = {
        {"add", l_add},
        {NULL, NULL},
    };
    luaL_newlib(L, l);
    return 1;
}

test.h

#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int test_add(int, int);

test.c

#include  "test.h"

int test_add(int x, int y)
{
    printf("test_add x:%d,y:%d\n", x, y);
    return x + y + 100;
}

3.makefile 文件
Makefile

CC ?= gcc
CFLAGS = -g -O2 -Wall -I$(LUA_INC)
SHARED := -fPIC --shared

TARGET = test.so

LUA_INC ?= /usr/local/src/lua-5.3.0/src

start:$(TARGET)

$(TARGET):lua-test.c test.c
	$(CC) $(CFLAGS) $(SHARED) $^ -o $@

clean:
	rm -rf *.so

4.整体目录结构
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值