lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hello, raksoras.

> I understand that C code generally should not store the pointer to a
> string returned by lua_tostring beyond the lifetime of the C function
> call.(PIL says "The lua_tostring function returns a pointer to an
> internal copy of the string. Lua ensures that this pointer is valid as
> long as the corresponding value is in the stack. When a C function
> returns, Lua clears its stack; therefore, as a rule, you should never
> store pointers to Lua strings outside the function that got them.")

> However, is this restriction strictly true if I can guarantee - from
> my code flow - that the original string in lua will continue to be in
> reachable (that is, it is not garbage collected) when my C function
> call returns?

> Here is my actual scenario: Luaw HTTP server uses Lua coroutines to
> handle multiple connections simultaneously. While generating response
> a Lua coroutine calls a C function with Lua string that the C function
> is eventually supposed to write to socket. But since the socket write
> may block, the C function actually uses async write API (libuv to be
> specific) to write to the socket. The function then returns
> immediately and the Lua coroutine that called the C function yields to
> suspend itself. When the socket is ready for the actual write, libuv's
> async API invokes a C callback that writes the string on the socket
> and then resumes the suspended coroutine.

> Is it safe to not make a copy of a lua string in C function in this case?

I  really  do  not  think  this  is  safe.  e.g. `sok:write("HELLO " ..
"WORLD")`. Result string has no anchor. In my binding I just make
Lua reference to string and unref it  in  write  callback [1].
Same  thing works if you want write array of strings. You do not copy
data but make reference to array. And it works With Lua >= 5.1
Also  for  Lua  5.3 and if you use userdata to store write request you
can use UserValue associated with this request.


[1] https://github.com/moteus/lua-lluv/blob/master/src/lluv_stream.c#L395-L399


---
Это сообщение проверено на вирусы антивирусом Avast.
http://www.avast.com