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