pointerscharffiluajit

access c char pointer to char pointer in luajit ffi


i am trying to access swiss ephemeris (aka sweph) from luajit ffi

i have successfully compiled swiss ephemeris into libswe.so and copied it to system library path

in my swisseph.lua file i require ffi and also load external library - libswe.so

now i need to access a char pointer to a char pointer, for a start

here is the lua code:

    local ffi = require('ffi')
    local swe = ffi.load('/usr/local/lib/libswe/libswe.so') -- ok
    ffi.cdef [[
      char *swe_version(char *svers);
    ]]

definition for swe_version is exact copy-paste from swiss ephemeris source code, .h file

sweph documentation states :

svers is a string variable with sufficient space to contain the version number (255 char)

first i tried:

    local ver = swe.swe_version -- type(ver) -> cdata
    print(ver) --> cdata<char *()>: 0x7f3f2d72b630 -- ok 

i believe this is memory address of pointer, to swe_version

if i do function call :

    local ver = swe.swe_version()

i get 'wrong number of arguments...'

so i added argument :

    local vers = { svers = {} }
    local ver = swe.swe_version(vers)

i tried some code examples, and google search produced some findings : c-code pointer to pointer has lua-equivalent as { p={} } table

and i also think that i need to convert char pointer to lua string, via ffi.new()

also tried ffi.cast()

other than that, i am unable to persuade luajit to spit a sweph version

how can one access a c char pointer to char pointer, using luajit ffi, and display it ?


Solution

  • First, you should allocate 256 byte buffer for version to be returned

    local ffi = require"ffi"
    local swe = ffi.load"/usr/local/lib/libswe/libswe.so"
    ffi.cdef"char *swe_version(char *svers)"
    local buf = ffi.new("char[?]", 256)  -- allocate the buffer
    swe.swe_version(buf)  -- fill the buffer with version string
    print(ffi.string(buf))  -- convert the buffer content to Lua string