Re: luajit string to char * conversion

  • From: Konstantin Olkhovskiy <lupus@xxxxxxxxxx>
  • To: luajit <luajit@xxxxxxxxxxxxx>
  • Date: Wed, 19 Nov 2014 13:30:18 +0400

2014-11-19 11:50 GMT+03:00 marcelo nicolet <marcelo.nicolet@xxxxxxxxx>:

>  Thank you, but the text you kindly pointed me to, reads like basic
> chinese to me. Not a single simple example...
>

Some examples can be found on the tutorial page [1].

> I must to think that cdata is some C native tipe data piece, and ct is
> some C data type. So, read in that way, it seems redundant. Also "pointers
> to addresses": roughly, what's the difference?
>
`cdata` can be described as a piece of lightuserdata, with underlying
stored C type known to the LuaJIT FFI.
If you call `type` on it, it should say "cdata". `ctype` is a type of
cdata, say "const char *", while cdata object
itself would hold an concrete instance of a pointer to character buffer.
`ffi.cast` is an analog of C cast. You
can cast a cdata of ctype "void *" to ctype "char *" (and you will get a
new cdata of new type, with same
pointer inside).

You can retrieve ctype using ffi.typeof. You can also cast Lua string to
"char *", but this will result in a cdata
pointer to LuaJIT internal memory buffer, so any modifications would result
in undefined behavior.

I still strongly recommend to read all the pages under "FFI Library", you
can avoid some basic mistakes. Bugs
in Lua software with heavy FFI usage are quite hard to debug.

[1] http://luajit.org/ext_ffi_tutorial.html

>  --
Regards,
Konstantin

Other related posts: