userdata_and_userpointers.rst 1.6 KB

12345678910111213141516171819202122232425262728293031323334
  1. .. _embedding_userdata_and_userpointers:
  2. =========================
  3. Userdata and UserPointers
  4. =========================
  5. Squirrel allows the host application put arbitrary data chunks into a Squirrel value, this is
  6. possible through the data type userdata.::
  7. SQUserPointer sq_newuserdata(HSQUIRRELVM v,SQUnsignedInteger size);
  8. When the function *sq_newuserdata* is called, Squirrel allocates a new userdata with the
  9. specified size, returns a pointer to his payload buffer and push the object in the stack; at
  10. this point the application can do whatever it want with this memory chunk, the VM will
  11. automatically take cake of the memory deallocation like for every other built-in type.
  12. A userdata can be passed to a function or stored in a table slot. By default Squirrel
  13. cannot manipulate directly userdata; however is possible to assign a delegate to it and
  14. define a behavior like it would be a table.
  15. Because the application would want to do something with the data stored in a userdata
  16. object when it get deleted, is possible to assign a callback that will be called by the VM
  17. just before deleting a certain userdata.
  18. This is done through the API call *sq_setreleasehook*.::
  19. typedef SQInteger (*SQRELEASEHOOK)(SQUserPointer,SQInteger size);
  20. void sq_setreleasehook(HSQUIRRELVM v,SQInteger idx,SQRELEASEHOOK hook);
  21. Another kind of userdata is the userpointer; this type is not a memory chunk like the
  22. normal userdata, but just a 'void*' pointer. It cannot have a delegate and is passed by
  23. value, so pushing a userpointer doesn't cause any memory allocation.::
  24. void sq_pushuserpointer(HSQUIRRELVM v,SQUserPointer p);