Search code examples
arrayspointersluaffiluajit

LuaJIT: pass pointer to existing 2D array of doubles from C to script?


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.


Solution

  • 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