Lua: efficient work (read / write) in C-style, dynamic arrays with C distribution in lua

Suppose I allocated a dynamic array of double C numbers in C / C ++ style, so I:

double *x; //Pointing to beginning of allocated memory
int size; //Size of array

Is it possible to write lua code (or even the C / C ++ code that will be used in lua) so that the built-in lua instance in C / C ++ can efficiently read and write the elements of this "view" in an array?

I just need support for the following C ++ operations:

double y = x[2]; //Reading
x[2] = 3.0; //Writing
int vecSize = x.size(); //Size of array

No memory management needed (and not required).

+3
source share
2 answers

Of course, export the pointer as userdata and set the metadata __index and __newindex.

+4
source

Mega Pall LuaJIT 2.0, FFI ( ).

C Lua, Lua. , LuaJIT:

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

LuaJIT, Lua, (size * sizeof(double)), __index __newindex array[i].

lightuserdata , , : value = get(array, i); set(array, i, value).

+3

Source: https://habr.com/ru/post/1789498/


All Articles