Advertisement
Guest User

objectmode

a guest
May 15th, 2012
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.57 KB | None | 0 0
  1. /*-
  2.  * Copyright (c) 2012 valsorym <[email protected]>.
  3.  * All rights reserved.
  4.  *
  5.  * Discussion on the forums.freebsd.org.
  6.  *  url: http://forums.freebsd.org/showthread.php?p=177208
  7.  */
  8.  
  9. /*
  10.  * Class prototype, and new/delete emulation in OOD ANSI C.
  11.  */
  12.  
  13. #ifndef OBJECTMODE_H
  14. #define OBJECTMODE_H
  15.  
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. #include <stdarg.h>
  19.  
  20. /* NEW TYPES */
  21. /* ************************************************************************* */
  22. /*
  23.  * Structure has size our future object, and it Constructor/Destructor
  24.  * memory point.
  25.  */
  26. typedef struct {
  27.     size_t size;
  28.     void *(*create)(void *, va_list *);
  29.     void *(*destroy)(void *);
  30. } w_class;
  31.  
  32. /* INTERFACE */
  33. /* ************************************************************************* */
  34.  
  35. /* IMPLEMENTATION */
  36. /* ************************************************************************* */
  37. /*
  38.  * Function find constructor point our class, and initialize memory section for
  39.  * it. Function has va_list arguments for initialization different objects.
  40.  */
  41. void
  42. *new(w_class *class, ...)
  43. {
  44.     void *p = NULL;
  45.    
  46.     if (class && class->create) {
  47.         /* Call constructor our future object. */
  48.         va_list app;
  49.         va_start(app, class);
  50.         p = class->create(class, &app);
  51.         va_end(app);
  52.     }
  53.  
  54.     return p;
  55. }
  56.  
  57. /*
  58.  * Free memory sector, when lived our object.
  59.  */
  60. void
  61. delete(void *obj)
  62. {
  63.     w_class **p = obj;
  64.    
  65.     if (obj && p && (*p)->destroy)
  66.         obj = (*p)->destroy(obj);
  67.        
  68.     free(obj);
  69. }
  70.  
  71. #endif
  72.  
  73. /* The End. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement