0

I want to manipulate existing 2D arrays of doubles directly in LuaJIT by passing a pointer to the script. I see it isn't possible to create pointers to existing data. Can I pass a pointer to an existing array of primitives from C to LuaJIT and read/write from there? I know the size of the array and data so just need to be able read/write the memory.

Community
  • 1
  • 1
PaulR
  • 706
  • 9
  • 27

1 Answers1

1

Sure you can! Here is a small test script, where I allocate and fill an array on the C side and I get a pointer in lua through a function.

// test.c
// gcc -std=c99 -O3 -Wall -fPIC -shared test.c -o libtest.so
#include <stdio.h>
#include <stdlib.h>

#define SIZE_A 10

double** get_pointer()
{
  double** a = malloc(SIZE_A * sizeof(*a));
  for (int i = 0; i < SIZE_A; ++i) {
    a[i] = malloc(SIZE_A * sizeof(*a[i]));
    for (int j = 0; j < SIZE_A; ++j) {
      a[i][j] = i*SIZE_A + j;
      printf("%.1f ", a[i][j]);
    }
    printf("\n");
  }

  printf("&a_c = %p\n", (void*)a);
  return a;
}

And the Lua script:

local ffi = require "ffi"
local testLib = ffi.load("./libtest.so")

ffi.cdef[[
  double** get_pointer();
]]

local ptr = ffi.new("double**")
ptr = testLib.get_pointer()
print(ptr)


local size_a = 10
for i=0,size_a-1 do
  for j=0,size_a-1 do
    io.write(ptr[i][j], ' ')
  end
  io.write('\n')
end

for i=0,size_a-1 do
  for j=0,size_a-1 do
    ptr[i][j] = 2 * ptr[i][j]
  end
end

for i=0,size_a-1 do
  for j=0,size_a-1 do
    io.write(ptr[i][j], ' ')
  end
  io.write('\n')
end
Ciprian Tomoiagă
  • 3,773
  • 4
  • 41
  • 65
  • 1
    you're welcome! note that it doesn't work if the array is statically allocated. Like saying `static double a[10][10]; return &a;`. I'm not sure why ... – Ciprian Tomoiagă Mar 06 '15 at 01:23
  • Thanks for following up with this additional info, this will no doubt prove useful for me and many future LuaJIT n00bs! :) – PaulR Mar 06 '15 at 23:30