take – How do I get what was given with define in lua FFI?

Question:

Many system programming functions on linux work with flags (for example, O_NONBLOCK ). But these flags must also be obtained! As far as I understand, flags in header files are defined using #define . Traditional something like ffi.C.O_NONBLOCK error, this is not a function or a global variable! In this case, the header file is loaded using the lcpp library. And how do you get these same define 's?

Answer:

You shouldn't use ffi.C. and ffi.lcpp_defs.

Example 1

Test1.lua file:

local lcpp = require("lcpp")
local ffi = require("ffi")

ffi.cdef([[
    #define MAX_SIZE 100
    typedef struct {
        int data[MAX_SIZE];
    } test_t;
]])

print("MAX_SIZE = " .. ffi.lcpp_defs.MAX_SIZE)

Result of work:

MAX_SIZE = 100

Example 2

Test2.lua file:

local lcpp = require("lcpp")
local ffi = require("ffi")

ffi.cdef("#include \"test.h\"")

print("FREQUENCY_MHZ = " .. ffi.lcpp_defs.FREQUENCY_MHZ)
print("FREQUENCY_KHZ = " .. ffi.lcpp_defs.FREQUENCY_KHZ)
print("_PACKED_ = " .. ffi.lcpp_defs._PACKED_)

Test.h file:

#ifndef TEST_H
#define TEST_H

#define FREQUENCY_MHZ 2
#define FREQUENCY_KHZ (FREQUENCY_MHZ * 1000)

#define _PACKED_ __attribute__((packed))

#endif // TEST_H

Result of work:

FREQUENCY_MHZ = 2
FREQUENCY_KHZ = (FREQUENCY_MHZ * 1000)
_PACKED_ = __attribute__((packed))

In general, everything works, but from the second example you can see that the complete preprocessing of the define 's is not happening. In fact, everything is not so bad here.

Example 3

Test3.lua file:

local ffi = require("ffi")
local lcpp = require("lcpp")

local data, state = lcpp.compile([[
    #define ROW_CNT 0x0F
    #define COL_CNT 0x0A
    #define DATA_CNT (ROW_CNT * COL_CNT)
    int data[DATA_CNT];
]])
local data_type = ffi.typeof(data)

print("data = " .. data)
print("ROW_CNT = " .. state.defines.ROW_CNT)
print("COL_CNT = " .. state.defines.COL_CNT)
print("DATA_CNT = " .. state.defines.DATA_CNT)
print("typeof(data) = " .. tostring(data_type))

Result of work:

data = int data[(15*10)];
ROW_CNT = 0x0F
COL_CNT = 0x0A
DATA_CNT = (ROW_CNT * COL_CNT)
typeof(data) = ctype<int[150]>

As you can see from this example, the dimension of the array is calculated correctly (150 elements).

Scroll to Top