Updated 2017-03-09 15:44:00 by SEH

George Peter Staplin: In a Tk project I needed to expose data structures and pointers to Tcl. The usual approach to do this is via a hash table with keys. I believe this is known as an opaque pointer. Some people have also suggested custom Tcl_Obj types. I found that for my needs I could do it via a much simpler method.

See mem_to_obj for the function that is used to store a structure/pointer in a ByteArray.

I use the following code in my project by #include'ing it:
 /* REVISION 289 */
 #include <string.h>
 #ifndef OBJ_TO_MEM_C
 #define OBJ_TO_MEM_C
 inline int
 obj_to_mem ( Tcl_Interp *interp, Tcl_Obj *obj, void *mem, size_t s, char *type_str ) {
  int len;
  unsigned char *bytes;

  bytes = Tcl_GetByteArrayFromObj (obj, &len);
  if (s != len) {
   Tcl_SetResult (interp, "object size is invalid for a ", TCL_STATIC);
   Tcl_AppendResult (interp, type_str, NULL);
   return TCL_ERROR;
  memcpy ((unsigned char *)mem, bytes, s);
  return TCL_OK;
 #endif /* OBJ_TO_MEM_C */

Here is an example use:
 Drawable d;
 GC gc;

 if (TCL_OK != obj_to_mem (interp, objv[1], &d, sizeof (Drawable), "Drawable"))
  return TCL_ERROR;

 if (TCL_OK != obj_to_mem (interp, objv[2], &gc, sizeof (GC), "GC"))
  return TCL_ERROR;

See also mem_to_obj