]> git.mxchange.org Git - simgear.git/blob - simgear/nasal/cppbind/Ghost.hxx
6a8ccfb8bf4a85c16659ea033fa3aedd73efd379
[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/function.hpp>
30 #include <boost/lambda/lambda.hpp>
31 #include <boost/utility/enable_if.hpp>
32
33 #include <map>
34
35 /**
36  * Bindings between C++ and the Nasal scripting language
37  */
38 namespace nasal
39 {
40
41   /**
42    * Traits for C++ classes exposed as Ghost. This is the basic template for
43    * raw types.
44    */
45   template<class T>
46   struct GhostTypeTraits
47   {
48     /** Whether the class is passed by shared pointer or raw pointer */
49     typedef boost::false_type::type is_shared;
50
51     /** The raw class type (Without any shared pointer) */
52     typedef T raw_type;
53   };
54
55   template<class T>
56   struct GhostTypeTraits<boost::shared_ptr<T> >
57   {
58     typedef boost::true_type::type is_shared;
59     typedef T raw_type;
60   };
61
62 #ifdef OSG_REF_PTR
63   template<class T>
64   struct GhostTypeTraits<osg::ref_ptr<T> >
65   {
66     typedef boost::true_type::type is_shared;
67     typedef T raw_type;
68   };
69 #endif
70
71 #ifdef SGSharedPtr_HXX
72   template<class T>
73   struct GhostTypeTraits<SGSharedPtr<T> >
74   {
75     typedef boost::true_type::type is_shared;
76     typedef T raw_type;
77   };
78 #endif
79
80   /**
81    * Policy for creating ghost instances from shared pointer objects.
82    */
83   template<class T>
84   struct SharedPointerPolicy
85   {
86     typedef typename GhostTypeTraits<T>::raw_type   raw_type;
87     typedef T                                       pointer;
88     typedef boost::false_type                       returns_dynamic_type;
89
90     /**
91      * Create a shared pointer on the heap to handle the reference counting for
92      * the passed shared pointer while it is used in Nasal space.
93      */
94     static T* createInstance(const T& ptr)
95     {
96       return new T(ptr);
97     }
98
99     static pointer getPtr(void* ptr)
100     {
101       if( ptr )
102         return *static_cast<T*>(ptr);
103       else
104         return pointer();
105     }
106
107     static raw_type* getRawPtr(void* ptr)
108     {
109       if( ptr )
110         return static_cast<T*>(ptr)->get();
111       else
112         return 0;
113     }
114
115     static raw_type* getRawPtr(const T& ptr)
116     {
117       return ptr.get();
118     }
119   };
120
121   /**
122    * Policy for creating ghost instances as raw objects on the heap.
123    */
124   template<class T>
125   struct RawPointerPolicy
126   {
127     typedef typename GhostTypeTraits<T>::raw_type   raw_type;
128     typedef raw_type*                               pointer;
129     typedef boost::true_type                        returns_dynamic_type;
130
131     /**
132      * Create a new object instance on the heap
133      */
134     static T* createInstance()
135     {
136       return new T();
137     }
138
139     static pointer getPtr(void* ptr)
140     {
141       BOOST_STATIC_ASSERT((boost::is_same<pointer, T*>::value));
142       return static_cast<T*>(ptr);
143     }
144
145     static raw_type* getRawPtr(void* ptr)
146     {
147       BOOST_STATIC_ASSERT((boost::is_same<raw_type, T>::value));
148       return static_cast<T*>(ptr);
149     }
150   };
151
152   namespace internal
153   {
154     /**
155      * Metadata for Ghost object types
156      */
157     class GhostMetadata
158     {
159       public:
160         /**
161          * Add a nasal base class to the ghost. Will be available in the ghosts
162          * parents array.
163          */
164         void addNasalBase(const naRef& parent)
165         {
166           assert( naIsHash(parent) );
167           _parents.push_back(parent);
168         }
169
170         bool isBaseOf(naGhostType* ghost_type) const
171         {
172           if( ghost_type == &_ghost_type )
173             return true;
174
175           for( DerivedList::const_iterator derived = _derived_classes.begin();
176                                            derived != _derived_classes.end();
177                                          ++derived )
178           {
179             if( (*derived)->isBaseOf(ghost_type) )
180               return true;
181           }
182
183           return false;
184         }
185
186       protected:
187
188         typedef std::vector<const GhostMetadata*> DerivedList;
189
190         const std::string   _name;
191         naGhostType         _ghost_type;
192         DerivedList         _derived_classes;
193         std::vector<naRef>  _parents;
194
195         explicit GhostMetadata(const std::string& name):
196           _name(name)
197         {
198
199         }
200
201         void addDerived(const GhostMetadata* derived)
202         {
203           assert(derived);
204           _derived_classes.push_back(derived);
205
206           SG_LOG
207           (
208             SG_NASAL,
209             SG_INFO,
210             "Ghost::addDerived: " <<_ghost_type.name << " -> " << derived->_name
211           );
212         }
213
214         naRef getParents(naContext c)
215         {
216           return nasal::to_nasal(c, _parents);
217         }
218     };
219   }
220
221   /**
222    * Context passed to a function/method being called from Nasal
223    */
224   struct CallContext
225   {
226     CallContext(naContext c, size_t argc, naRef* args):
227       c(c),
228       argc(argc),
229       args(args)
230     {}
231
232     template<class T>
233     T get(size_t index, const T& def = T()) const
234     {
235       if( index >= argc )
236         return def;
237
238       return from_nasal<T>(c, args[index]);
239     }
240
241     template<class T>
242     T require(size_t index) const
243     {
244       if( index >= argc )
245         naRuntimeError(c, "Missing required arg #%d", index);
246
247       return from_nasal<T>(c, args[index]);
248     }
249
250     naContext   c;
251     size_t      argc;
252     naRef      *args;
253   };
254
255   /**
256    * Class for exposing C++ objects to Nasal
257    *
258    * @code{cpp}
259    * // Example class to be exposed to Nasal
260    * class MyClass
261    * {
262    *   public:
263    *     void setX(int x);
264    *     int getX() const;
265    *
266    *     naRef myMember(naContext c, int argc, naRef* args);
267    * }
268    *
269    * void exposeClasses()
270    * {
271    *   // Register a nasal ghost type for MyClass. This needs to be done only
272    *   // once before creating the first ghost instance.
273    *   Ghost<MyClass>::init("MyClass")
274    *     // Members can be exposed by getters and setters
275    *     .member("x", &MyClass::getX, &MyClass::setX)
276    *     // For readonly variables only pass a getter
277    *     .member("x_readonly", &MyClass::getX)
278    *     // It is also possible to expose writeonly members
279    *     .member("x_writeonly", &MyClass::setX)
280    *     // Methods use a slightly different syntax - The pointer to the member
281    *     // function has to be passed as template argument
282    *     .method<&MyClass::myMember>("myMember");
283    * }
284    * @endcode
285    */
286   template<class T>
287   class Ghost:
288     public internal::GhostMetadata,
289     protected boost::mpl::if_< typename GhostTypeTraits<T>::is_shared,
290                                SharedPointerPolicy<T>,
291                                RawPointerPolicy<T> >::type
292   {
293     public:
294       typedef T                                                   value_type;
295       typedef typename GhostTypeTraits<T>::raw_type               raw_type;
296       typedef typename Ghost::pointer                             pointer;
297       typedef naRef (raw_type::*member_func_t)(const CallContext&);
298       typedef naRef (*free_func_t)(raw_type&, const CallContext&);
299       typedef boost::function<naRef(naContext, raw_type&)>        getter_t;
300       typedef boost::function<void(naContext, raw_type&, naRef)>  setter_t;
301
302       /**
303        * A ghost member. Can consist either of getter and/or setter functions
304        * for exposing a data variable or a single callable function.
305        */
306       struct member_t
307       {
308         member_t():
309           func(0)
310         {}
311
312         member_t( const getter_t& getter,
313                   const setter_t& setter,
314                   naCFunction func = 0 ):
315           getter( getter ),
316           setter( setter ),
317           func( func )
318         {}
319
320         member_t(naCFunction func):
321           func( func )
322         {}
323
324         getter_t    getter;
325         setter_t    setter;
326         naCFunction func;
327       };
328
329       typedef std::map<std::string, member_t> MemberMap;
330
331       /**
332        * Register a new ghost type.
333        *
334        * @note Only intialize each ghost type once!
335        *
336        * @param name    Descriptive name of the ghost type.
337        */
338       static Ghost& init(const std::string& name)
339       {
340         assert( !getSingletonPtr() );
341
342         getSingletonHolder().reset( new Ghost(name) );
343         return *getSingletonPtr();
344       }
345
346       /**
347        * Register a base class for this ghost. The base class needs to be
348        * registers on its own before it can be used as base class.
349        *
350        * @tparam BaseGhost  Type of base class already wrapped into Ghost class
351        *                    (Ghost<Base>)
352        *
353        * @code{cpp}
354        * Ghost<MyBase>::init("MyBase");
355        * Ghost<MyClass>::init("MyClass")
356        *   .bases<Ghost<MyBase> >();
357        * @endcode
358        */
359       template<class BaseGhost>
360       typename boost::enable_if_c
361         <    boost::is_base_of<GhostMetadata, BaseGhost>::value
362           && boost::is_base_of<typename BaseGhost::raw_type, raw_type>::value,
363           Ghost
364         >::type&
365       bases()
366       {
367         BaseGhost* base = BaseGhost::getSingletonPtr();
368         base->addDerived
369         (
370           this,
371           // Both ways of retrieving the address of a static member function
372           // should be legal but not all compilers know this.
373           // g++-4.4.7+ has been tested to work with both versions
374 #if defined(GCC_VERSION) && GCC_VERSION < 40407
375           // The old version of g++ used on Jenkins (16.11.2012) only compiles
376           // this version.
377           &getTypeFor<BaseGhost>
378 #else
379           // VS (2008, 2010, ... ?) only allow this version.
380           &Ghost::getTypeFor<BaseGhost>
381 #endif
382         );
383
384         // Replace any getter that is not available in the current class.
385         // TODO check if this is the correct behavior of function overriding
386         for( typename BaseGhost::MemberMap::const_iterator member =
387                base->_members.begin();
388                member != base->_members.end();
389              ++member )
390         {
391           if( _members.find(member->first) == _members.end() )
392             _members[member->first] = member_t
393             (
394               member->second.getter,
395               member->second.setter,
396               member->second.func
397             );
398         }
399
400         return *this;
401       }
402
403       /**
404        * Register a base class for this ghost. The base class needs to be
405        * registers on its own before it can be used as base class.
406        *
407        * @tparam Base   Type of base class (Base as used in Ghost<Base>)
408        *
409        * @code{cpp}
410        * Ghost<MyBase>::init("MyBase");
411        * Ghost<MyClass>::init("MyClass")
412        *   .bases<MyBase>();
413        * @endcode
414        */
415       template<class Base>
416       typename boost::enable_if_c
417         <   !boost::is_base_of<GhostMetadata, Base>::value
418           && boost::is_base_of<typename Ghost<Base>::raw_type, raw_type>::value,
419           Ghost
420         >::type&
421       bases()
422       {
423         return bases< Ghost<Base> >();
424       }
425
426       /**
427        * Register an existing Nasal class/hash as base class for this ghost.
428        *
429        * @param parent  Nasal hash/class
430        */
431       Ghost& bases(const naRef& parent)
432       {
433         addNasalBase(parent);
434         return *this;
435       }
436
437       /**
438        * Register a member variable by passing a getter and/or setter method.
439        *
440        * @param field   Name of member
441        * @param getter  Getter for variable
442        * @param setter  Setter for variable (Pass 0 to prevent write access)
443        *
444        */
445       template<class Var>
446       Ghost& member( const std::string& field,
447                      Var (raw_type::*getter)() const,
448                      void (raw_type::*setter)(Var) = 0 )
449       {
450         member_t m;
451         if( getter )
452         {
453           naRef (*to_nasal_)(naContext, Var) = &nasal::to_nasal;
454
455           // Getter signature: naRef(naContext, raw_type&)
456           m.getter = boost::bind(to_nasal_, _1, boost::bind(getter, _2));
457         }
458
459         if( setter )
460         {
461           Var (*from_nasal_)(naContext, naRef) = &nasal::from_nasal;
462
463           // Setter signature: void(naContext, raw_type&, naRef)
464           m.setter = boost::bind(setter, _2, boost::bind(from_nasal_, _1, _3));
465         }
466
467         return member(field, m.getter, m.setter);
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>(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 a member function.
509        *
510        * @note Because only function pointers can be registered as Nasal
511        *       functions it is needed to pass the function pointer as template
512        *       argument. This allows us to create a separate instance of the
513        *       MemberFunctionWrapper for each registered function and therefore
514        *       provides us with the needed static functions to be passed on to
515        *       Nasal.
516        *
517        * @tparam func   Pointer to member function being registered.
518        *
519        * @code{cpp}
520        * class MyClass
521        * {
522        *   public:
523        *     naRef myMethod(naContext c, int argc, naRef* args);
524        * }
525        *
526        * Ghost<MyClass>::init("Test")
527        *   .method<&MyClass::myMethod>("myMethod");
528        * @endcode
529        */
530       template<member_func_t func>
531       Ghost& method(const std::string& name)
532       {
533         _members[name].func = &MemberFunctionWrapper<func>::call;
534         return *this;
535       }
536
537       /**
538        * Register a free function as member function. The object instance is
539        * passed as additional first argument.
540        *
541        * @tparam func   Pointer to free function being registered.
542        *
543        * @note Due to a severe bug in Visual Studio it is not possible to create
544        *       a specialization of #method for free function pointers and
545        *       member function pointers at the same time. Do overcome this
546        *       limitation we had to use a different name for this function.
547        *
548        * @code{cpp}
549        * class MyClass;
550        * naRef myMethod(MyClass& obj, naContext c, int argc, naRef* args);
551        *
552        * Ghost<MyClass>::init("Test")
553        *   .method_func<&myMethod>("myMethod");
554        * @endcode
555        */
556       template<free_func_t func>
557       Ghost& method_func(const std::string& name)
558       {
559         _members[name].func = &FreeFunctionWrapper<func>::call;
560         return *this;
561       }
562
563       // TODO use variadic template when supporting C++11
564       /**
565        * Create a Nasal instance of this ghost.
566        *
567        * @param c   Active Nasal context
568        */
569       static naRef create( naContext c )
570       {
571         return makeGhost(c, Ghost::createInstance());
572       }
573
574       /**
575        * Create a Nasal instance of this ghost.
576        *
577        * @param c   Active Nasal context
578        * @param a1  Parameter used for creating new instance
579        */
580       template<class A1>
581       static naRef create( naContext c, const A1& a1 )
582       {
583         return makeGhost(c, Ghost::createInstance(a1));
584       }
585
586       /**
587        * Nasal callback for creating a new instance of this ghost.
588        */
589       static naRef f_create(naContext c, naRef me, int argc, naRef* args)
590       {
591         return create(c);
592       }
593
594       static bool isBaseOf(naGhostType* ghost_type)
595       {
596         if( !ghost_type )
597           return false;
598
599         return getSingletonPtr()->GhostMetadata::isBaseOf(ghost_type);
600       }
601
602       static bool isBaseOf(naRef obj)
603       {
604         return isBaseOf( naGhost_type(obj) );
605       }
606
607       /**
608        * Convert Nasal object to C++ object. To get a valid object the passed
609        * Nasal objects has to be derived class of the target class (Either
610        * derived in C++ or in Nasal using a 'parents' vector)
611        */
612       static pointer fromNasal(naContext c, naRef me)
613       {
614         // Check if it's a ghost and if it can be converted
615         if( isBaseOf( naGhost_type(me) ) )
616           return Ghost::getPtr( naGhost_ptr(me) );
617
618         // Now if it is derived from a ghost (hash with ghost in parent vector)
619         // TODO handle recursive parents
620         else if( naIsHash(me) )
621         {
622           naRef na_parents = naHash_cget(me, const_cast<char*>("parents"));
623           if( !naIsVector(na_parents) )
624           {
625             SG_LOG(SG_NASAL, SG_DEBUG, "Missing 'parents' vector for ghost");
626             return pointer();
627           }
628
629           typedef std::vector<naRef> naRefs;
630           naRefs parents = from_nasal<naRefs>(c, na_parents);
631           for( naRefs::const_iterator parent = parents.begin();
632                                       parent != parents.end();
633                                     ++parent )
634           {
635             if( isBaseOf(naGhost_type(*parent)) )
636               return Ghost::getPtr( naGhost_ptr(*parent) );
637           }
638         }
639
640         return pointer();
641       }
642
643     private:
644
645       template<class>
646       friend class Ghost;
647
648       typedef naGhostType* (*type_checker_t)(const raw_type*);
649       typedef std::vector<type_checker_t> DerivedList;
650       DerivedList _derived_types;
651
652       void addDerived( const internal::GhostMetadata* derived_meta,
653                        const type_checker_t& derived_info )
654       {
655         GhostMetadata::addDerived(derived_meta);
656         _derived_types.push_back(derived_info);
657       }
658
659       template<class BaseGhost>
660       static
661       typename boost::enable_if
662         < boost::is_polymorphic<typename BaseGhost::raw_type>,
663           naGhostType*
664         >::type
665       getTypeFor(const typename BaseGhost::raw_type* base)
666       {
667         // Check first if passed pointer can by converted to instance of class
668         // this ghost wraps.
669         if(   !boost::is_same
670                  < typename BaseGhost::raw_type,
671                    typename Ghost::raw_type
672                  >::value
673             && dynamic_cast<const typename Ghost::raw_type*>(base) != base )
674           return 0;
675
676         // Now check if we can further downcast to one of our derived classes.
677         for( typename DerivedList::reverse_iterator
678                derived = getSingletonPtr()->_derived_types.rbegin();
679                derived != getSingletonPtr()->_derived_types.rend();
680              ++derived )
681         {
682           naGhostType* ghost_type =
683             (*derived)( static_cast<const typename Ghost::raw_type*>(base) );
684           if( ghost_type )
685             return ghost_type;
686         }
687
688         // If base is not an instance of any derived class, this class has to
689         // be the dynamic type.
690         return &getSingletonPtr()->_ghost_type;
691       }
692
693       template<class BaseGhost>
694       static
695       typename boost::disable_if
696         < boost::is_polymorphic<typename BaseGhost::raw_type>,
697           naGhostType*
698         >::type
699       getTypeFor(const typename BaseGhost::raw_type* base)
700       {
701         // For non polymorphic classes there is no possibility to get the actual
702         // dynamic type, therefore we can only use its static type.
703         return &BaseGhost::getSingletonPtr()->_ghost_type;
704       }
705
706       static Ghost* getSingletonPtr()
707       {
708         return getSingletonHolder().get();
709       }
710
711       static raw_type& requireObject(naContext c, naRef me)
712       {
713         raw_type* obj = Ghost::getRawPtr( fromNasal(c, me) );
714         naGhostType* ghost_type = naGhost_type(me);
715
716         if( !obj )
717           naRuntimeError
718           (
719             c,
720             "method called on object of wrong type: is '%s' expected '%s'",
721             ghost_type ? ghost_type->name : "unknown",
722             getSingletonPtr()->_ghost_type.name
723           );
724
725         return *obj;
726       }
727
728       /**
729        * Wrapper class to enable registering pointers to member functions as
730        * Nasal function callbacks. We need to use the function pointer as
731        * template parameter to ensure every registered function gets a static
732        * function which can be passed to Nasal.
733        */
734       template<member_func_t func>
735       struct MemberFunctionWrapper
736       {
737         /**
738          * Called from Nasal upon invocation of the according registered
739          * function. Forwards the call to the passed object instance.
740          */
741         static naRef call(naContext c, naRef me, int argc, naRef* args)
742         {
743           return (requireObject(c, me).*func)(CallContext(c, argc, args));
744         }
745       };
746
747       /**
748        * Wrapper class to enable registering pointers to free functions (only
749        * external linkage). We need to use the function pointer as template
750        * parameter to ensure every registered function gets a static function
751        * which can be passed to Nasal. Even though we just wrap another simple
752        * function pointer this intermediate step is need to be able to retrieve
753        * the object the function call belongs to and pass it along as argument.
754        */
755       template<free_func_t func>
756       struct FreeFunctionWrapper
757       {
758         /**
759          * Called from Nasal upon invocation of the according registered
760          * function. Forwards the call to the passed function pointer and passes
761          * the required parameters.
762          */
763         static naRef call(naContext c, naRef me, int argc, naRef* args)
764         {
765           return func(requireObject(c, me), CallContext(c, argc, args));
766         }
767       };
768
769       typedef std::auto_ptr<Ghost> GhostPtr;
770       MemberMap _members;
771
772       explicit Ghost(const std::string& name):
773         GhostMetadata( name )
774       {
775         _ghost_type.destroy = &destroyGhost;
776         _ghost_type.name = _name.c_str();
777         _ghost_type.get_member = &getMember;
778         _ghost_type.set_member = &setMember;
779       }
780
781       static GhostPtr& getSingletonHolder()
782       {
783         static GhostPtr instance;
784         return instance;
785       }
786
787       static naRef makeGhost(naContext c, void *ptr)
788       {
789         if( !Ghost::getRawPtr(ptr) )
790           return naNil();
791
792         naGhostType* ghost_type = 0;
793         if( Ghost::returns_dynamic_type::value )
794           // For pointer policies already returning instances of an object with
795           // the dynamic type of this Ghost's raw_type the type is always the
796           // same.
797           ghost_type = &getSingletonPtr()->_ghost_type;
798         else
799           // If wrapping eg. shared pointers the users passes an already
800           // existing instance of an object which will then be hold be a new
801           // shared pointer. We therefore have to check for the dynamic type
802           // of the object as it might differ from the passed static type.
803           ghost_type = getTypeFor<Ghost>( Ghost::getRawPtr(ptr) );
804
805         if( !ghost_type )
806           return naNil();
807
808         return naNewGhost2(c, ghost_type, ptr);
809       }
810
811       static void destroyGhost(void *ptr)
812       {
813         delete (T*)ptr;
814       }
815
816       /**
817        * Callback for retrieving a ghost member.
818        */
819       static const char* getMember(naContext c, void* g, naRef key, naRef* out)
820       {
821         const std::string key_str = nasal::from_nasal<std::string>(c, key);
822         if( key_str == "parents" )
823         {
824           if( getSingletonPtr()->_parents.empty() )
825             return 0;
826
827           *out = getSingletonPtr()->getParents(c);
828           return "";
829         }
830
831         typename MemberMap::iterator member =
832           getSingletonPtr()->_members.find(key_str);
833
834         if( member == getSingletonPtr()->_members.end() )
835           return 0;
836
837         if( member->second.func )
838           *out = nasal::to_nasal(c, member->second.func);
839         else if( !member->second.getter.empty() )
840           *out = member->second.getter(c, *Ghost::getRawPtr(g));
841         else
842           return "Read-protected member";
843
844         return "";
845       }
846
847       /**
848        * Callback for writing to a ghost member.
849        */
850       static void setMember(naContext c, void* g, naRef field, naRef val)
851       {
852         const std::string key = nasal::from_nasal<std::string>(c, field);
853         typename MemberMap::iterator member =
854           getSingletonPtr()->_members.find(key);
855
856         if( member == getSingletonPtr()->_members.end() )
857           naRuntimeError(c, "ghost: No such member: %s", key.c_str());
858         if( member->second.setter.empty() )
859           naRuntimeError(c, "ghost: Write protected member: %s", key.c_str());
860
861         member->second.setter(c, *Ghost::getRawPtr(g), val);
862       }
863   };
864
865 } // namespace nasal
866
867 #endif /* SG_NASAL_GHOST_HXX_ */