]> git.mxchange.org Git - simgear.git/blob - simgear/nasal/cppbind/Ghost.hxx
cppbind: rework to allow binding nearly everything.
[simgear.git] / simgear / nasal / cppbind / Ghost.hxx
1 ///@file
2 /// Expose C++ objects to Nasal as ghosts
3 ///
4 // Copyright (C) 2012  Thomas Geymayer <tomgey@gmail.com>
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Library General Public
8 // License as published by the Free Software Foundation; either
9 // version 2 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Library General Public License for more details.
15 //
16 // You should have received a copy of the GNU Library General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301, USA
19
20 #ifndef SG_NASAL_GHOST_HXX_
21 #define SG_NASAL_GHOST_HXX_
22
23 #include "from_nasal.hxx"
24 #include "to_nasal.hxx"
25
26 #include <simgear/debug/logstream.hxx>
27
28 #include <boost/bind.hpp>
29 #include <boost/call_traits.hpp>
30 #include <boost/function.hpp>
31 #include <boost/lambda/lambda.hpp>
32 #include <boost/mpl/has_xxx.hpp>
33 #include <boost/preprocessor/iteration/iterate.hpp>
34 #include <boost/shared_ptr.hpp>
35 #include <boost/utility/enable_if.hpp>
36
37 #include <map>
38
39 /**
40  * Bindings between C++ and the Nasal scripting language
41  */
42 namespace nasal
43 {
44
45   namespace internal
46   {
47     /**
48      * Metadata for Ghost object types
49      */
50     class GhostMetadata
51     {
52       public:
53         /**
54          * Add a nasal base class to the ghost. Will be available in the ghosts
55          * parents array.
56          */
57         void addNasalBase(const naRef& parent)
58         {
59           assert( naIsHash(parent) );
60           _parents.push_back(parent);
61         }
62
63         bool isBaseOf(naGhostType* ghost_type) const
64         {
65           if( ghost_type == &_ghost_type )
66             return true;
67
68           for( DerivedList::const_iterator derived = _derived_classes.begin();
69                                            derived != _derived_classes.end();
70                                          ++derived )
71           {
72             if( (*derived)->isBaseOf(ghost_type) )
73               return true;
74           }
75
76           return false;
77         }
78
79       protected:
80
81         typedef std::vector<const GhostMetadata*> DerivedList;
82
83         const std::string   _name;
84         naGhostType         _ghost_type;
85         DerivedList         _derived_classes;
86         std::vector<naRef>  _parents;
87
88         explicit GhostMetadata(const std::string& name):
89           _name(name)
90         {
91
92         }
93
94         void addDerived(const GhostMetadata* derived)
95         {
96           assert(derived);
97           _derived_classes.push_back(derived);
98
99           SG_LOG
100           (
101             SG_NASAL,
102             SG_INFO,
103             "Ghost::addDerived: " <<_ghost_type.name << " -> " << derived->_name
104           );
105         }
106
107         naRef getParents(naContext c)
108         {
109           return nasal::to_nasal(c, _parents);
110         }
111     };
112
113     /**
114      * Hold callable method and convert to Nasal function if required.
115      */
116     class MethodHolder
117     {
118       public:
119         virtual ~MethodHolder() {}
120         virtual naRef get_naRef(naContext c) = 0;
121     };
122
123     BOOST_MPL_HAS_XXX_TRAIT_DEF(element_type)
124   }
125
126   /**
127    * Context passed to a function/method being called from Nasal
128    */
129   struct CallContext
130   {
131     CallContext(naContext c, size_t argc, naRef* args):
132       c(c),
133       argc(argc),
134       args(args)
135     {}
136
137     /**
138      * Get the argument with given index if it exists. Otherwise returns the
139      * passed default value.
140      *
141      * @tparam T    Type of argument (converted using ::from_nasal)
142      * @param index Index of requested argument
143      * @param def   Default value returned if too few arguments available
144      */
145     template<class T>
146     typename from_nasal_ptr<T>::return_type
147     getArg(size_t index, const T& def = T()) const
148     {
149       if( index >= argc )
150         return def;
151
152       return (*from_nasal_ptr<T>::get())(c, args[index]);
153     }
154
155     /**
156      * Get the argument with given index. Raises a Nasal runtime error if there
157      * are to few arguments available.
158      */
159     template<class T>
160     typename from_nasal_ptr<T>::return_type
161     requireArg(size_t index) const
162     {
163       if( index >= argc )
164         naRuntimeError(c, "Missing required arg #%d", index);
165
166       return (*from_nasal_ptr<T>::get())(c, args[index]);
167     }
168
169     naContext   c;
170     size_t      argc;
171     naRef      *args;
172   };
173
174   /**
175    * Class for exposing C++ objects to Nasal
176    *
177    * @code{cpp}
178    * // Example class to be exposed to Nasal
179    * class MyClass
180    * {
181    *   public:
182    *     void setX(int x);
183    *     int getX() const;
184    *
185    *     int myMember();
186    *     void doSomethingElse(const nasal::CallContext& ctx);
187    * }
188    * typedef boost::shared_ptr<MyClass> MyClassPtr;
189    *
190    * std::string myOtherFreeMember(int num);
191    *
192    * void exposeClasses()
193    * {
194    *   // Register a nasal ghost type for MyClass. This needs to be done only
195    *   // once before creating the first ghost instance. The exposed class needs
196    *   // to be wrapped inside a shared pointer, eg. boost::shared_ptr.
197    *   Ghost<MyClassPtr>::init("MyClass")
198    *     // Members can be exposed by getters and setters
199    *     .member("x", &MyClass::getX, &MyClass::setX)
200    *     // For readonly variables only pass a getter
201    *     .member("x_readonly", &MyClass::getX)
202    *     // It is also possible to expose writeonly members
203    *     .member("x_writeonly", &MyClass::setX)
204    *     // Methods can be nearly anything callable and accepting a reference
205    *     // to an instance of the class type. (member functions, free functions
206    *     // and anything else bindable using boost::function and boost::bind)
207    *     .method("myMember", &MyClass::myMember)
208    *     .method("doSomething", &MyClass::doSomethingElse)
209    *     .method("other", &myOtherFreeMember);
210    * }
211    * @endcode
212    */
213   template<class T>
214   class Ghost:
215     public internal::GhostMetadata
216   {
217       BOOST_STATIC_ASSERT( internal::has_element_type<T>::value );
218
219     public:
220       typedef typename T::element_type                              raw_type;
221       typedef T                                                     pointer;
222       typedef naRef (raw_type::*member_func_t)(const CallContext&);
223       typedef naRef (*free_func_t)(raw_type&, const CallContext&);
224       typedef boost::function<naRef(naContext, raw_type&)>          getter_t;
225       typedef boost::function<void(naContext, raw_type&, naRef)>    setter_t;
226       typedef boost::function<naRef(raw_type&, const CallContext&)> method_t;
227       typedef boost::shared_ptr<internal::MethodHolder> MethodHolderPtr;
228
229       class MethodHolder:
230         public internal::MethodHolder
231       {
232         public:
233           MethodHolder():
234             _naRef(naNil())
235           {}
236
237           explicit MethodHolder(const method_t& method):
238             _method(method),
239             _naRef(naNil())
240           {}
241
242           virtual naRef get_naRef(naContext c)
243           {
244             if( naIsNil(_naRef) )
245             {
246               _naRef = naNewFunc(c, naNewCCodeU(c, &MethodHolder::call, this));
247               naSave(c, _naRef);
248             }
249             return _naRef;
250           }
251
252         protected:
253           method_t  _method;
254           naRef     _naRef;
255
256           static naRef call( naContext c,
257                              naRef me,
258                              int argc,
259                              naRef* args,
260                              void* user_data )
261           {
262             MethodHolder* holder = static_cast<MethodHolder*>(user_data);
263             if( !holder )
264               naRuntimeError(c, "invalid method holder!");
265
266             return holder->_method
267             (
268               requireObject(c, me),
269               CallContext(c, argc, args)
270             );
271           }
272       };
273
274       /**
275        * A ghost member. Can consist either of getter and/or setter functions
276        * for exposing a data variable or a single callable function.
277        */
278       struct member_t
279       {
280         member_t()
281         {}
282
283         member_t( const getter_t& getter,
284                   const setter_t& setter,
285                   const MethodHolderPtr& func = MethodHolderPtr() ):
286           getter( getter ),
287           setter( setter ),
288           func( func )
289         {}
290
291         explicit member_t(const MethodHolderPtr& func):
292           func( func )
293         {}
294
295         getter_t        getter;
296         setter_t        setter;
297         MethodHolderPtr func;
298       };
299
300       typedef std::map<std::string, member_t> MemberMap;
301
302       /**
303        * Register a new ghost type.
304        *
305        * @note Only intialize each ghost type once!
306        *
307        * @param name    Descriptive name of the ghost type.
308        */
309       static Ghost& init(const std::string& name)
310       {
311         assert( !getSingletonPtr() );
312
313         getSingletonHolder().reset( new Ghost(name) );
314         return *getSingletonPtr();
315       }
316
317       /**
318        * Register a base class for this ghost. The base class needs to be
319        * registers on its own before it can be used as base class.
320        *
321        * @tparam BaseGhost  Type of base class already wrapped into Ghost class
322        *                    (Ghost<BasePtr>)
323        *
324        * @code{cpp}
325        * Ghost<MyBasePtr>::init("MyBase");
326        * Ghost<MyClassPtr>::init("MyClass")
327        *   .bases<Ghost<MyBasePtr> >();
328        * @endcode
329        */
330       template<class BaseGhost>
331       typename boost::enable_if
332         <
333           boost::is_base_of<GhostMetadata, BaseGhost>,
334           Ghost
335         >::type&
336       bases()
337       {
338         BOOST_STATIC_ASSERT
339         ((
340           boost::is_base_of<typename BaseGhost::raw_type, raw_type>::value
341         ));
342
343         BaseGhost* base = BaseGhost::getSingletonPtr();
344         base->addDerived
345         (
346           this,
347           // Both ways of retrieving the address of a static member function
348           // should be legal but not all compilers know this.
349           // g++-4.4.7+ has been tested to work with both versions
350 #if defined(GCC_VERSION) && GCC_VERSION < 40407
351           // The old version of g++ used on Jenkins (16.11.2012) only compiles
352           // this version.
353           &getTypeFor<BaseGhost>
354 #else
355           // VS (2008, 2010, ... ?) only allow this version.
356           &Ghost::getTypeFor<BaseGhost>
357 #endif
358         );
359
360         // Replace any getter that is not available in the current class.
361         // TODO check if this is the correct behavior of function overriding
362         for( typename BaseGhost::MemberMap::const_iterator member =
363                base->_members.begin();
364                member != base->_members.end();
365              ++member )
366         {
367           if( _members.find(member->first) == _members.end() )
368             _members[member->first] = member_t
369             (
370               member->second.getter,
371               member->second.setter,
372               member->second.func
373             );
374         }
375
376         return *this;
377       }
378
379       /**
380        * Register a base class for this ghost. The base class needs to be
381        * registers on its own before it can be used as base class.
382        *
383        * @tparam Base   Type of base class (Base as used in Ghost<BasePtr>)
384        *
385        * @code{cpp}
386        * Ghost<MyBasePtr>::init("MyBase");
387        * Ghost<MyClassPtr>::init("MyClass")
388        *   .bases<MyBasePtr>();
389        * @endcode
390        */
391       template<class Base>
392       typename boost::disable_if
393         <
394           boost::is_base_of<GhostMetadata, Base>,
395           Ghost
396         >::type&
397       bases()
398       {
399         BOOST_STATIC_ASSERT
400         ((
401           boost::is_base_of<typename Ghost<Base>::raw_type, raw_type>::value
402         ));
403
404         return bases< Ghost<Base> >();
405       }
406
407       /**
408        * Register an existing Nasal class/hash as base class for this ghost.
409        *
410        * @param parent  Nasal hash/class
411        */
412       Ghost& bases(const naRef& parent)
413       {
414         addNasalBase(parent);
415         return *this;
416       }
417
418       /**
419        * Register a member variable by passing a getter and/or setter method.
420        *
421        * @param field   Name of member
422        * @param getter  Getter for variable
423        * @param setter  Setter for variable (Pass 0 to prevent write access)
424        *
425        */
426       template<class Ret, class Param>
427       Ghost& member( const std::string& field,
428                      Ret (raw_type::*getter)() const,
429                      void (raw_type::*setter)(Param) )
430       {
431         member_t m;
432         if( getter )
433         {
434           // Getter signature: naRef(naContext, raw_type&)
435           m.getter = boost::bind
436           (
437             to_nasal_ptr<Ret>::get(),
438             _1,
439             boost::bind(getter, _2)
440           );
441         }
442
443         if( setter )
444         {
445           // Setter signature: void(naContext, raw_type&, naRef)
446           m.setter = boost::bind
447           (
448             setter,
449             _2,
450             boost::bind(from_nasal_ptr<Param>::get(), _1, _3)
451           );
452         }
453
454         return member(field, m.getter, m.setter);
455       }
456
457       /**
458        * Register a read only member variable.
459        *
460        * @param field   Name of member
461        * @param getter  Getter for variable
462        */
463       template<class Ret>
464       Ghost& member( const std::string& field,
465                      Ret (raw_type::*getter)() const )
466       {
467         return member<Ret, Ret>(field, getter, 0);
468       }
469
470       /**
471        * Register a write only member variable.
472        *
473        * @param field   Name of member
474        * @param setter  Setter for variable
475        */
476       template<class Var>
477       Ghost& member( const std::string& field,
478                      void (raw_type::*setter)(Var) )
479       {
480         return member<Var, Var>(field, 0, setter);
481       }
482
483       /**
484        * Register a member variable by passing a getter and/or setter method.
485        *
486        * @param field   Name of member
487        * @param getter  Getter for variable
488        * @param setter  Setter for variable (Pass empty to prevent write access)
489        *
490        */
491       Ghost& member( const std::string& field,
492                      const getter_t& getter,
493                      const setter_t& setter = setter_t() )
494       {
495         if( !getter.empty() || !setter.empty() )
496           _members[field] = member_t(getter, setter);
497         else
498           SG_LOG
499           (
500             SG_NASAL,
501             SG_WARN,
502             "Member '" << field << "' requires a getter or setter"
503           );
504         return *this;
505       }
506
507       /**
508        * Register anything that accepts an object instance and a
509        * nasal::CallContext and returns naRef as method.
510        *
511        * @code{cpp}
512        * class MyClass
513        * {
514        *   public:
515        *     naRef myMethod(const nasal::CallContext& ctx);
516        * }
517        *
518        * Ghost<MyClassPtr>::init("Test")
519        *   .method("myMethod", &MyClass::myMethod);
520        * @endcode
521        */
522       Ghost& method(const std::string& name, const method_t& func)
523       {
524         _members[name].func.reset( new MethodHolder(func) );
525         return *this;
526       }
527
528       /**
529        * Register anything that accepts an object instance and a
530        * nasal::CallContext whith automatic conversion of the return type to
531        * Nasal.
532        *
533        * @code{cpp}
534        * class MyClass;
535        * void doIt(const MyClass& c, const nasal::CallContext& ctx);
536        *
537        * Ghost<MyClassPtr>::init("Test")
538        *   .method("doIt", &doIt);
539        * @endcode
540        */
541       template<class Ret>
542       Ghost& method
543       (
544         const std::string& name,
545         const boost::function<Ret (raw_type&, const CallContext&)>& func
546       )
547       {
548         return method(name, boost::bind(method_invoker<Ret>, func, _1, _2));
549       }
550
551 #define BOOST_PP_ITERATION_LIMITS (0, 9)
552 #define BOOST_PP_FILENAME_1 <simgear/nasal/cppbind/detail/functor_templates.hxx>
553 #include BOOST_PP_ITERATE()
554
555       // TODO use variadic template when supporting C++11
556       // TODO check if default constructor exists
557 //      static naRef create( naContext c )
558 //      {
559 //        return makeGhost(c, createInstance());
560 //      }
561
562       /**
563        * Create a Nasal instance of this ghost.
564        *
565        * @param c   Active Nasal context
566        * @param a1  Parameter used for creating new instance
567        */
568       template<class A1>
569       static naRef create( naContext c, const A1& a1 )
570       {
571         return makeGhost(c, createInstance(a1));
572       }
573
574       /**
575        * Nasal callback for creating a new instance of this ghost.
576        */
577       static naRef f_create(naContext c, naRef me, int argc, naRef* args)
578       {
579         return create(c);
580       }
581
582       static bool isBaseOf(naGhostType* ghost_type)
583       {
584         if( !ghost_type )
585           return false;
586
587         return getSingletonPtr()->GhostMetadata::isBaseOf(ghost_type);
588       }
589
590       static bool isBaseOf(naRef obj)
591       {
592         return isBaseOf( naGhost_type(obj) );
593       }
594
595       /**
596        * Convert Nasal object to C++ object. To get a valid object the passed
597        * Nasal objects has to be derived class of the target class (Either
598        * derived in C++ or in Nasal using a 'parents' vector)
599        */
600       static pointer fromNasal(naContext c, naRef me)
601       {
602         // Check if it's a ghost and if it can be converted
603         if( isBaseOf( naGhost_type(me) ) )
604           return getPtr( naGhost_ptr(me) );
605
606         // Now if it is derived from a ghost (hash with ghost in parent vector)
607         else if( naIsHash(me) )
608         {
609           naRef na_parents = naHash_cget(me, const_cast<char*>("parents"));
610           if( !naIsVector(na_parents) )
611           {
612             SG_LOG(SG_NASAL, SG_DEBUG, "Missing 'parents' vector for ghost");
613             return pointer();
614           }
615
616           typedef std::vector<naRef> naRefs;
617           naRefs parents = from_nasal<naRefs>(c, na_parents);
618           for( naRefs::const_iterator parent = parents.begin();
619                                       parent != parents.end();
620                                     ++parent )
621           {
622             pointer ptr = fromNasal(c, *parent);
623             if( ptr )
624               return ptr;
625           }
626         }
627
628         return pointer();
629       }
630
631     private:
632
633       template<class>
634       friend class Ghost;
635
636       typedef naGhostType* (*type_checker_t)(const raw_type*);
637       typedef std::vector<type_checker_t> DerivedList;
638       DerivedList _derived_types;
639
640       /**
641        * Create a shared pointer on the heap to handle the reference counting
642        * for the passed shared pointer while it is used in Nasal space.
643        */
644       static pointer* createInstance(const pointer& ptr)
645       {
646         return ptr ? new pointer(ptr) : 0;
647       }
648
649       static pointer getPtr(void* ptr)
650       {
651         if( ptr )
652           return *static_cast<pointer*>(ptr);
653         else
654           return pointer();
655       }
656
657       static raw_type* getRawPtr(void* ptr)
658       {
659         if( ptr )
660           return static_cast<pointer*>(ptr)->get();
661         else
662           return 0;
663       }
664
665       static raw_type* getRawPtr(const pointer& ptr)
666       {
667         return ptr.get();
668       }
669
670       void addDerived( const internal::GhostMetadata* derived_meta,
671                        const type_checker_t& derived_info )
672       {
673         GhostMetadata::addDerived(derived_meta);
674         _derived_types.push_back(derived_info);
675       }
676
677       template<class BaseGhost>
678       static
679       typename boost::enable_if
680         < boost::is_polymorphic<typename BaseGhost::raw_type>,
681           naGhostType*
682         >::type
683       getTypeFor(const typename BaseGhost::raw_type* base)
684       {
685         // Check first if passed pointer can by converted to instance of class
686         // this ghost wraps.
687         if(   !boost::is_same
688                  < typename BaseGhost::raw_type,
689                    typename Ghost::raw_type
690                  >::value
691             && dynamic_cast<const typename Ghost::raw_type*>(base) != base )
692           return 0;
693
694         // Now check if we can further downcast to one of our derived classes.
695         for( typename DerivedList::reverse_iterator
696                derived = getSingletonPtr()->_derived_types.rbegin();
697                derived != getSingletonPtr()->_derived_types.rend();
698              ++derived )
699         {
700           naGhostType* ghost_type =
701             (*derived)( static_cast<const typename Ghost::raw_type*>(base) );
702           if( ghost_type )
703             return ghost_type;
704         }
705
706         // If base is not an instance of any derived class, this class has to
707         // be the dynamic type.
708         return &getSingletonPtr()->_ghost_type;
709       }
710
711       template<class BaseGhost>
712       static
713       typename boost::disable_if
714         < boost::is_polymorphic<typename BaseGhost::raw_type>,
715           naGhostType*
716         >::type
717       getTypeFor(const typename BaseGhost::raw_type* base)
718       {
719         // For non polymorphic classes there is no possibility to get the actual
720         // dynamic type, therefore we can only use its static type.
721         return &BaseGhost::getSingletonPtr()->_ghost_type;
722       }
723
724       static Ghost* getSingletonPtr()
725       {
726         return getSingletonHolder().get();
727       }
728
729       static raw_type& requireObject(naContext c, naRef me)
730       {
731         raw_type* obj = getRawPtr( fromNasal(c, me) );
732         naGhostType* ghost_type = naGhost_type(me);
733
734         if( !obj )
735           naRuntimeError
736           (
737             c,
738             "method called on object of wrong type: is '%s' expected '%s'",
739             ghost_type ? ghost_type->name : "unknown",
740             getSingletonPtr()->_ghost_type.name
741           );
742
743         return *obj;
744       }
745
746       /**
747        * Invoke a method which returns a value and convert it to Nasal.
748        */
749       template<class Ret>
750       static
751       typename boost::disable_if<boost::is_void<Ret>, naRef>::type
752       method_invoker
753       (
754         const boost::function<Ret (raw_type&, const CallContext&)>& func,
755         raw_type& obj,
756         const CallContext& ctx
757       )
758       {
759         return (*to_nasal_ptr<Ret>::get())(ctx.c, func(obj, ctx));
760       };
761
762       /**
763        * Invoke a method which returns void and "convert" it to nil.
764        */
765       template<class Ret>
766       static
767       typename boost::enable_if<boost::is_void<Ret>, naRef>::type
768       method_invoker
769       (
770         const boost::function<Ret (raw_type&, const CallContext&)>& func,
771         raw_type& obj,
772         const CallContext& ctx
773       )
774       {
775         func(obj, ctx);
776         return naNil();
777       };
778
779       /**
780        * Extract argument by index from nasal::CallContext and convert to given
781        * type.
782        */
783       template<class Arg>
784       static
785       typename boost::disable_if<
786         boost::is_same<Arg, const CallContext&>,
787         typename from_nasal_ptr<Arg>::return_type
788       >::type
789       arg_from_nasal(const CallContext& ctx, size_t index)
790       {
791         return ctx.requireArg<Arg>(index);
792       };
793
794       /**
795        * Specialization to pass through nasal::CallContext.
796        */
797       template<class Arg>
798       static
799       typename boost::enable_if<
800         boost::is_same<Arg, const CallContext&>,
801         typename from_nasal_ptr<Arg>::return_type
802       >::type
803       arg_from_nasal(const CallContext& ctx, size_t)
804       {
805         return ctx;
806       };
807
808       typedef std::auto_ptr<Ghost> GhostPtr;
809       MemberMap _members;
810
811       explicit Ghost(const std::string& name):
812         GhostMetadata( name )
813       {
814         _ghost_type.destroy = &destroyGhost;
815         _ghost_type.name = _name.c_str();
816         _ghost_type.get_member = &getMember;
817         _ghost_type.set_member = &setMember;
818       }
819
820       static GhostPtr& getSingletonHolder()
821       {
822         static GhostPtr instance;
823         return instance;
824       }
825
826       static naRef makeGhost(naContext c, void *ptr)
827       {
828         if( getRawPtr(ptr) )
829         {
830           // We are wrapping shared pointers to already existing objects which
831           // will then be hold be a new shared pointer. We therefore have to
832           // check for the dynamic type of the object as it might differ from
833           // the passed static type.
834           naGhostType* ghost_type = getTypeFor<Ghost>( getRawPtr(ptr) );
835
836           if( ghost_type )
837             return naNewGhost2(c, ghost_type, ptr);
838         }
839
840         destroyGhost(ptr);
841         return naNil();
842       }
843
844       static void destroyGhost(void *ptr)
845       {
846         delete static_cast<pointer*>(ptr);
847       }
848
849       /**
850        * Callback for retrieving a ghost member.
851        */
852       static const char* getMember(naContext c, void* g, naRef key, naRef* out)
853       {
854         const std::string key_str = nasal::from_nasal<std::string>(c, key);
855         if( key_str == "parents" )
856         {
857           if( getSingletonPtr()->_parents.empty() )
858             return 0;
859
860           *out = getSingletonPtr()->getParents(c);
861           return "";
862         }
863
864         typename MemberMap::iterator member =
865           getSingletonPtr()->_members.find(key_str);
866
867         if( member == getSingletonPtr()->_members.end() )
868           return 0;
869
870         if( member->second.func )
871           *out = member->second.func->get_naRef(c);
872         else if( !member->second.getter.empty() )
873           *out = member->second.getter(c, *getRawPtr(g));
874         else
875           return "Read-protected member";
876
877         return "";
878       }
879
880       /**
881        * Callback for writing to a ghost member.
882        */
883       static void setMember(naContext c, void* g, naRef field, naRef val)
884       {
885         const std::string key = nasal::from_nasal<std::string>(c, field);
886         typename MemberMap::iterator member =
887           getSingletonPtr()->_members.find(key);
888
889         if( member == getSingletonPtr()->_members.end() )
890           naRuntimeError(c, "ghost: No such member: %s", key.c_str());
891         else if( member->second.setter.empty() )
892           naRuntimeError(c, "ghost: Write protected member: %s", key.c_str());
893         else if( member->second.func )
894           naRuntimeError(c, "ghost: Write to function: %s", key.c_str());
895
896         member->second.setter(c, *getRawPtr(g), val);
897       }
898   };
899
900 } // namespace nasal
901
902 #endif /* SG_NASAL_GHOST_HXX_ */