4

Say I have this C function:

__declspec(dllexport) const char* GetStr()
{
    static char buff[32]

    // Fill the buffer with some string here

    return buff;
}

And this simple Lua module:

local mymodule = {}

local ffi = require("ffi")

ffi.cdef[[
    const char* GetStr();
]]

function mymodule.get_str()
    return ffi.C.GetStr()
end

return mymodule

How can I get the returned string from the C function as a Lua string here:

local mymodule = require "mymodule"

print(mymodule.get_str())
SLC
  • 2,167
  • 2
  • 28
  • 46
  • What are you getting it as now? What does that code do that you don't want? – Etan Reisner Aug 31 '14 at 23:32
  • Currently when I print I get `cdata: 0x00000001` instead of the string. From the documentation I'm supposed to use `ffi.string(buff [,len])` to get the actual string. But when I do that the application crashes. – SLC Aug 31 '14 at 23:37
  • 1
    Show the `ffi.string` call you were trying, and the backtrace/etc. from the crash. Ideally also the code that fills the string. – Etan Reisner Aug 31 '14 at 23:45
  • @EtanReisner Turns out that this was happening because of one simple mistake in my code (one of those copy>paste mistakes). I apologize for the inconvenience. The example works fine now with the answer from hugomg. – SLC Aug 31 '14 at 23:47

1 Answers1

7

The ffi.string function apparently does the conversion you are looking for.

function mymodule.get_str()
    local c_str = ffi.C.GetStr()
    return ffi.string(c_str)
end

If you are getting a crash, then make sure that your C string is null terminated and, in your case, has at most 31 characterss (so as to not overflow its buffer).

ElementW
  • 804
  • 8
  • 23
hugomg
  • 68,213
  • 24
  • 160
  • 246
  • I tried that but the application crashes. I thought I was doing something wrong :-/ – SLC Aug 31 '14 at 23:38
  • 1
    maybe your string is too long and is overflowing the buffer? – hugomg Aug 31 '14 at 23:39
  • 2
    Turns out that I miscalculated something and an integer was returned instead. Thank you all for your answers and I apologize for the inconvenience. – SLC Aug 31 '14 at 23:45
  • 1
    No need to apologize. There is always the possibility that the question will be useful for someone in the future. :) – hugomg Sep 01 '14 at 00:07
  • what to do if the string is longer than 31 chars? – Aftershock May 31 '15 at 19:34
  • 2
    The 31 characters limitation is because OP's code stores the string on a 32-byte buffer. You should be able to pass strings of any length to `ffi.string` – hugomg May 31 '15 at 19:43
  • please note, ffi.string also has a second 'len' parameter, so it can also be used with non-null-terminated strings. – Dmitry Vyal Apr 22 '16 at 09:30