Reputation: 69
Is it possible to access contents of heap memory in Lua by passing it a pointer to memory address allocated by malloc
function in C?
I have tried this :
int *j=(int *)malloc(sizeof(int));
j[0]=5;
passing (j
as a pointer to Lua), then Lua access contents at memory location pointed by pointer j
.
Upvotes: 3
Views: 2409
Reputation: 1171
What do you actually want to do? Your question seems to ask about moving data from C to Lua. Your comments suggest that you want to share memory between two separate processes.
If you just want to use some C with Lua, then you should write and extension (and use userdata to move data around). For example, if you have a library written in C and you want to use it in Lua, you will need to extend Lua with a module wrapping the library. This is covered in Part IV of PIL. When using an extension, there is only one process so memory is easily shared between C and Lua.
If you really need to share data between two processes, you will need to find some kind of IPC that works for you. Using a socket is an obvious choice, for that you can use LuaSocket. If you want a pub/sub, then you could try LCM, which supports both C and Lua.
Upvotes: 1
Reputation: 72402
There is no built-in support for that.
You can write your own support in C by exporting a version of malloc
to Lua that creates memory buffers as userdata and provides suitable metamethods for easy access of the contents. (But use lua_newuserdata
instead malloc
.)
A few of these have appeared in the Lua mailing list. See for instance
bytes at http://lua-users.org/lists/lua-l/2011-06/msg00114.html
lbuffer at http://lua-users.org/lists/lua-l/2011-10/msg00209.html
Upvotes: 3