lib/sod.h: New macro `SOD_INSTBASE' to find the allocated base address.
authorMark Wooding <mdw@distorted.org.uk>
Sat, 15 Aug 2015 15:14:32 +0000 (16:14 +0100)
committerMark Wooding <mdw@distorted.org.uk>
Sat, 15 Aug 2015 15:14:32 +0000 (16:14 +0100)
This turns out to be useful, e.g., for freeing dynamically allocated
objects.  A destructor method might usefully say something like

free(SOD_INSTBASE(me));

after actually releasing any other resources.

lib/sod.h

index 12c7817..6a444e9 100644 (file)
--- a/lib/sod.h
+++ b/lib/sod.h
@@ -109,11 +109,8 @@ struct sod_chain {
  *
  * Use:                Finds an instance's base address given a pointer to one of
  *             its ichains, if you know precisely the instance's class and
- *             which chain you're pointing to.  If you don't, then (a)
- *
- *               @(char *)(p) - (p)->_vt->_base@
- *
- *             will do the job just fine, and (b) you'll have the wrong
+ *             which chain you're pointing to.  If you don't, then (a) you
+ *             want @SOD_INSTBASE@ below, and (b) you'll have the wrong
  *             ilayout anyway.
  *
  *             This macro is not intended to be used directly outside of
@@ -126,6 +123,23 @@ struct sod_chain {
   ((struct cls##__ilayout *)                                           \
    ((char *)(p) - offsetof(struct cls##__ilayout, chead)))
 
+/* --- @SOD_INSTBASE@ --- *
+ *
+ * Arguments:  @p@ = pointer to an instance (i.e., the address of one of its
+ *                     instance chains)
+ *
+ * Returns:    The base address of @p@'s instance layout.
+ *
+ * Use:                Finds the base address of an instance.  If you know the
+ *             dynamic class of the object then @SOD_ILAYOUT@ is faster.  If
+ *             you don't, this is the right macro, but your options for
+ *             doing something sensible with the result are limited, mostly
+ *             to simple memory management operations such as freeing or
+ *             zeroizing the instance structure.
+ */
+
+#define SOD_INSTBASE(p) ((void *)((char *)(p) - (p)->_vt->_base))
+
 /*----- Utility macros ----------------------------------------------------*/
 
 /* --- @SOD_CLASSOF@ --- *