• call lua function from c and called back to c


    Just a simple example:


    --The  c file:

    #include <stdio.h>

    #include "lua.h"

    #include "luaconf.h"

    #include "lualib.h"

    #include "lauxlib.h"

    #include "math.h"


    static int l_sin (lua_State *L) {

    double d = lua_tonumber(L, 1);  /* get argument */

       lua_pushnumber(L, sin(d));  /* push result */

        return 1 /* number of results */

    }


    int main()

    {

    float pi = 3.1415926;

    float pidiv6 = pi / 6;

    float pidiv4 = pi / 4;


    float rt = 0;


    lua_State *L = luaL_newstate();

    luaL_openlibs(L);


    lua_pushcfunction(L, l_sin); //Lua know the address of l_sin in c context

    lua_setglobal(L, "mysin"); //map l_sin to mysin will be called in lua context


    if ( !luaL_dofile(L, "./cal.lua") ) {

    printf("load cal.lua successful ");

    } else {

    printf("error load file: %s ", lua_tostring(L, -1));

            return -1;

    }


    lua_getglobal(L, "lsin");

    lua_pushnumber(L, pidiv4);

    if ( !lua_pcall(L, 1, 1, 0) ) {

    rt = lua_tonumber(L, -1);

    } else {

    printf("error : %s ", lua_tostring(L, -1));

            return -1;

    }


    printf("rt = %f ", rt);


    return 0;

    }


    --cal.lua

    print("start...")
    function lsin ( angle )
    return mysin(angle)
    end
    print("end...")


    ==output==

    start...
    end...
    load cal.lua successful
    rt = 0.707107


    //Actually a more simpler way is to call mysin directly without cal.lua

    lua_getglobal(L, "mysin");

    lua_pushnumber(L, pidiv4);

    if ( !lua_pcall(L, 110) ) {

    rt = lua_tonumber(L, -1);

    else {

    printf("error : %s ", lua_tostring(L, -1));

            return -1;

    }



  • 相关阅读:
    [转]Vetur can't find `tsconfig.json` or `jsconfig.json` in d:VueProjectsmyroute.
    疾病检验的概率的问题
    约束优化方法之拉格朗日乘子法与KKT条件
    GloVe与word2vec
    RNN、LSTM、GRU
    SVM 常见问题
    深度学习常用优化器算法Optimizer详解
    树模型-常见问题点
    leetcode 打家劫舍
    node 图片处理库 sharp
  • 原文地址:https://www.cnblogs.com/mfmdaoyou/p/6800598.html
Copyright © 2020-2023  润新知