Re: luajit string to char * conversion

  • From: Florian Weimer <fw@xxxxxxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Sat, 22 Nov 2014 23:44:22 +0100

* marcelo nicolet:

> I catched the trick: when the argument will not be modified, declaring
> it const does the job.
> But when it will be modified (as in my example for recv() ) to have in
> the middle of lua code a call to malloc() and then to free() is not a
> "good thing" to my taste.

At least it's explicit about the lifetime of the temporary copy, and
it doesn't drive the garbage collector forward.

> What about
> local v = ffi.new( "char[?]", bufsize )
> Is it ok?
> TIA

Yes, but you still have to copy the string, and make sure that you
deal with the terminating NUL byte.

> PS: what if malloc() cannot allocate any memory? NULL from malloc
> comes as nil to lua code?

Correct (if malloc does indeed return NULL—usually, the kernel kills
entire processes if it runs out of memory).

Other related posts: