Lua FFI Combat

Source: Internet
Author: User

transferred from: http://blog.csdn.net/weiwangchao_/article/details/16880401

Origin

The FFI library is the most important extension library in Luajit. It allows external C functions to be called from pure LUA code, using C data structures. With it, you don't have to write a LUA extension library like the LUA standard math library. Frees developers from the heavy lifting of developing LUA Extensions C libraries (language/feature binding libraries). about FFI

The FFI library, which allows external C functions to be called from Pure LUA code, uses C data structures.

The FFI library minimizes the need to manually write heavy lua/c bindings using C. There is no need to learn a separate/extra binding language-it parses the general C declaration. This can be cut and pasted directly from the C header or reference manual. Its task is to bind a large library, but does not need to tinker with the weak binding generator.

The FFI is tightly integrated into the Luajit (almost impossible as a standalone module). The JIT compiler generates code that directly accesses the C data structure for LUA code, equivalent to the code that a C compiler should produce. In JIT-compiled code, the call to the C function can be processed inline, unlike the LUA/C API-based function call.

This page will briefly describe how the FFI library is used. Excitation Example: calling an external C function

It's really easy to call an external C library function:

①local FFI = require ("FFI") 
②ffi.cdef[[
  int printf (const char* FMT, ...);]
③ffi. c.printf ("Hello%s!", "World")

The above procedure is as follows:

① loading the FFI library
② adds a function declaration to the function. The part that is contained in the ' brackets ' pair is the standard C syntax
: ③ calls the named C function--very simple

In fact, the implementation behind is far from so simple: ③ uses the standard C Library's namespace Ffi.c. The namespace is indexed by the symbol name ("printf"), and the standard C library is automatically bound. The index result is a special type of object that executes the printf function when it is called. The arguments passed to this function are automatically converted from LUA objects to the corresponding C type.

Ok, using printf () is not a spectacular example. You may also use Io.write () and String.Format (). But you have this idea ... The following is an example of a Windows platform popup message box:

Local FFI = require ("FFI") ffi.cdef[[int messageboxa (void *w, const char *txt, const char *cap, int type);]] FFI. C.messageboxa (Nil, "Hello world!", "Test", 0)

bing! Once again, far from being so simple, no?

Compared to the effort required to use the LUA/C API to bind functions: Create an external C file, add a C function, traverse and examine the parameters passed by Lua, and invoke this real function,

the traditional processing method adds a list of module functions and corresponding names, adds a luaopen_* function, and registers all the module functions, compiles and links to a dynamic library (DLL), migrates the library files to the correct path, writes LUA code, loads modules, etc... Finally, the binding function is called.

Yo. (Very uncomfortable.) ) Excitation Example: using C data Structures

The FFI library allows you to create and access C data structures. Of course, its main application is the C function interface. However, it can also be used independently.

Lua is built on top of the advanced data types. They are flexible, scalable, and dynamic. That's why we all love Lua. Alas, when you need a low-level data structure for a particular task, this may be inefficient. For example, an array of very large different structures needs to be implemented with a large table that stores very many small tables. This requires a lot of memory overhead and performance overhead.

Here is a sketch of a library, manipulating a color map, and a benchmark. First, the plain version of Lua is as follows:

Local floor = Math.floor local function image_ramp_green (n) Local img = {} Local F = 255/(n-1) for i=1,n do img[i] = {R ed = 0, Green = Floor ((i-1) *f), blue = 0, alpha = 255} end return IMG End local function Image_to_grey (IMG, n) for I=1, n do local y = floor (0.3*img[i].red + 0.59*img[i].green + 0.11*img[i].blue) img[i].red = y; Img[i].green = y; Img[i].blue = y end end Local N = 400*400 local img = Image_ramp_green (n) for i=1,1000 do Image_to_grey (IMG, N) end

The above code creates a 160.000-pixel table, each of which is a table that holds 4 numeric values ranging from 0 to 255. First, create a picture of a green ramp (1 D, to simplify), and then do 1000 grayscale transformations. Really stupid, but I need a simple example ...

The following is the FFI version code. Where the modified part is highlighted in bold:

①local FFI = require ("FFI")
ffi.cdef[[
typedef struct {uint8_t red, green, blue, alpha;} Rgba_pixel;
]

②local function Image_ramp_green (n)
  local img = ffi.new ("rgba_pixel[?]", N)
  local f = 255/(n-1)
③  For i=0,n-1 do
④  img[i].green = i*f
    img[i].alpha = 255
  end
  return img
end

Local function Image_to_grey (IMG, n)
③for i=0,n-1 do
⑤   local y = 0.3*img[i].red + 0.59*img[i].green + 0.11*img[i ].blue
    img[i].red = y; img[i].green = y; img[i].blue = y
  end
End

Local N = 400*400
local img = IM Age_ramp_green (n)
for i=1,1000 do
  Image_to_grey (IMG, n)
end

Ok, this is not too difficult:

① first, load the FFI library and declare the underlying data type. Here we select a data structure that holds 4 byte fields, each consisting of 4x8 rgba pixels.

② creates this data structure directly through Ffi.new (), where '? ' is a placeholder that changes the number of array elements.

The ③C data is based on 0 (zero-based), so the index must be 0 to n-1. You may need to allocate more elements, rather than simplifying the transformation of first-class code.

④ because of the ffi.new () default 0 padding (zero-fills) array, we only need to set the green and Alpha fields.

⑤ call Math.floor () can be omitted because the floating-point number has been truncated to 0 when converted to an integer. This process implicitly occurs when the data is stored in each pixel field.

Now let's look at the major impact changes:

First, memory consumption drops from 22M to 640K (4004004 bytes). 35x less. So, the table does have a significant overhead. BTW (by the Way: incidentally): Original LUA

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.