2 /// Expose C++ objects to Nasal as ghosts
4 // Copyright (C) 2012 Thomas Geymayer <tomgey@gmail.com>
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.
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.
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
20 #ifndef SG_NASAL_GHOST_HXX_
21 #define SG_NASAL_GHOST_HXX_
23 #include "NasalCallContext.hxx"
24 #include "NasalObjectHolder.hxx"
26 #include <simgear/debug/logstream.hxx>
27 #include <simgear/structure/SGWeakReferenced.hxx>
28 #include <simgear/structure/SGWeakPtr.hxx>
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>
42 inline T* get_pointer(boost::weak_ptr<T> const& p)
44 return p.lock().get();
48 inline T* get_pointer(SGWeakPtr<T> const& p)
50 return p.lock().get();
54 inline T* get_pointer(osg::observer_ptr<T> const& p)
62 * Bindings between C++ and the Nasal scripting language
69 * Metadata for Ghost object types
75 * Add a nasal base class to the ghost. Will be available in the ghosts
78 void addNasalBase(const naRef& parent)
80 assert( naIsHash(parent) );
81 _parents.push_back(parent);
84 bool isBaseOf(naGhostType* ghost_type, bool& is_weak) const
86 if( ghost_type == _ghost_type_strong_ptr )
92 if( ghost_type == _ghost_type_weak_ptr )
98 for( DerivedList::const_iterator derived = _derived_classes.begin();
99 derived != _derived_classes.end();
102 if( (*derived)->isBaseOf(ghost_type, is_weak) )
111 typedef std::vector<const GhostMetadata*> DerivedList;
113 const std::string _name_strong,
115 const naGhostType *_ghost_type_strong_ptr,
116 *_ghost_type_weak_ptr;
117 DerivedList _derived_classes;
118 std::vector<naRef> _parents;
120 GhostMetadata( const std::string& name,
121 const naGhostType* ghost_type_strong,
122 const naGhostType* ghost_type_weak ):
124 _name_weak(name + " (weak ref)"),
125 _ghost_type_strong_ptr(ghost_type_strong),
126 _ghost_type_weak_ptr(ghost_type_weak)
131 void addDerived(const GhostMetadata* derived)
134 _derived_classes.push_back(derived);
140 "Ghost::addDerived: " << _name_strong << " -> "
141 << derived->_name_strong
145 naRef getParents(naContext c)
147 return nasal::to_nasal(c, _parents);
152 * Hold callable method and convert to Nasal function if required.
155 public SGWeakReferenced
158 virtual ~MethodHolder() {}
160 naRef get_naRef(naContext c)
163 _obj.reset(createNasalObject(c));
164 return _obj.get_naRef();
170 virtual naRef createNasalObject(naContext c) = 0;
173 BOOST_MPL_HAS_XXX_TRAIT_DEF(element_type)
178 typedef typename boost::remove_cv<
179 typename boost::remove_reference<T>::type
183 template<class T1, class T2>
184 struct reduced_is_same:
185 public boost::is_same<typename reduced_type<T1>::type, T2>
189 typedef SGSharedPtr<internal::MethodHolder> MethodHolderPtr;
190 typedef SGWeakPtr<internal::MethodHolder> MethodHolderWeakPtr;
193 * Class for exposing C++ objects to Nasal
196 * // Example class to be exposed to Nasal
204 * void doSomethingElse(const nasal::CallContext& ctx);
206 * typedef boost::shared_ptr<MyClass> MyClassPtr;
208 * std::string myOtherFreeMember(int num);
210 * void exposeClasses()
212 * // Register a nasal ghost type for MyClass. This needs to be done only
213 * // once before creating the first ghost instance. The exposed class needs
214 * // to be wrapped inside a shared pointer, eg. boost::shared_ptr.
215 * Ghost<MyClassPtr>::init("MyClass")
216 * // Members can be exposed by getters and setters
217 * .member("x", &MyClass::getX, &MyClass::setX)
218 * // For readonly variables only pass a getter
219 * .member("x_readonly", &MyClass::getX)
220 * // It is also possible to expose writeonly members
221 * .member("x_writeonly", &MyClass::setX)
222 * // Methods can be nearly anything callable and accepting a reference
223 * // to an instance of the class type. (member functions, free functions
224 * // and anything else bindable using boost::function and boost::bind)
225 * .method("myMember", &MyClass::myMember)
226 * .method("doSomething", &MyClass::doSomethingElse)
227 * .method("other", &myOtherFreeMember);
233 public internal::GhostMetadata
235 // Shared pointer required for Ghost (no weak pointer!)
236 BOOST_STATIC_ASSERT((shared_ptr_traits<T>::is_strong::value));
239 typedef typename T::element_type raw_type;
240 typedef typename shared_ptr_traits<T>::strong_ref strong_ref;
241 typedef typename shared_ptr_traits<T>::weak_ref weak_ref;
242 typedef naRef (raw_type::*member_func_t)(const CallContext&);
243 typedef naRef (*free_func_t)(raw_type&, const CallContext&);
244 typedef boost::function<naRef(raw_type&, naContext)> getter_t;
245 typedef boost::function<void( raw_type&, naContext, naRef)> setter_t;
246 typedef boost::function<naRef(raw_type&, const CallContext&)> method_t;
247 typedef boost::function<bool( raw_type&,
250 naRef& )> fallback_getter_t;
251 typedef boost::function<bool( raw_type&,
254 naRef )> fallback_setter_t;
257 public internal::MethodHolder
260 explicit MethodHolder(const method_t& method):
266 typedef SGSharedPtr<MethodHolder> SharedPtr;
267 typedef SGWeakPtr<MethodHolder> WeakPtr;
271 virtual naRef createNasalObject(naContext c)
283 static void destroyHolder(void* user_data)
285 delete static_cast<WeakPtr*>(user_data);
288 static naRef call( naContext c,
294 WeakPtr* holder_weak = static_cast<WeakPtr*>(user_data);
296 naRuntimeError(c, "invalid method holder!");
300 SharedPtr holder = holder_weak->lock();
302 throw std::runtime_error("holder has expired");
304 return holder->_method
306 requireObject(c, me),
307 CallContext(c, argc, args)
310 catch(const std::exception& ex)
312 naRuntimeError(c, "Fatal error in method call: %s", ex.what());
316 naRuntimeError(c, "Unknown exception in method call.");
324 * A ghost member. Can consist either of getter and/or setter functions
325 * for exposing a data variable or a single callable function.
332 member_t( const getter_t& getter,
333 const setter_t& setter,
334 const MethodHolderPtr& func = MethodHolderPtr() ):
340 explicit member_t(const MethodHolderPtr& func):
346 MethodHolderPtr func;
349 typedef std::map<std::string, member_t> MemberMap;
352 * Register a new ghost type.
354 * @note Only intialize each ghost type once!
356 * @param name Descriptive name of the ghost type.
358 static Ghost& init(const std::string& name)
360 getSingletonHolder().reset( new Ghost(name) );
361 return *getSingletonPtr();
365 * Check whether ghost type has already been initialized.
369 return getSingletonPtr();
373 * Register a base class for this ghost. The base class needs to be
374 * registers on its own before it can be used as base class.
376 * @tparam BaseGhost Type of base class already wrapped into Ghost class
380 * Ghost<MyBasePtr>::init("MyBase");
381 * Ghost<MyClassPtr>::init("MyClass")
382 * .bases<Ghost<MyBasePtr> >();
385 template<class BaseGhost>
386 typename boost::enable_if
388 boost::is_base_of<GhostMetadata, BaseGhost>,
395 boost::is_base_of<typename BaseGhost::raw_type, raw_type>::value
398 BaseGhost* base = BaseGhost::getSingletonPtr();
402 // Both ways of retrieving the address of a static member function
403 // should be legal but not all compilers know this.
404 // g++-4.4.7+ has been tested to work with both versions
405 #if defined(SG_GCC_VERSION) && SG_GCC_VERSION < 40407
406 // The old version of g++ used on Jenkins (16.11.2012) only compiles
408 &getTypeFor<BaseGhost>
410 // VS (2008, 2010, ... ?) only allow this version.
411 &Ghost::getTypeFor<BaseGhost>
415 // Replace any getter that is not available in the current class.
416 // TODO check if this is the correct behavior of function overriding
417 for( typename BaseGhost::MemberMap::const_iterator member =
418 base->_members.begin();
419 member != base->_members.end();
422 if( _members.find(member->first) == _members.end() )
423 _members[member->first] = member_t
425 member->second.getter,
426 member->second.setter,
431 if( !_fallback_setter )
432 _fallback_setter = base->_fallback_setter;
433 if( !_fallback_getter )
434 _fallback_getter = base->_fallback_getter;
440 * Register a base class for this ghost. The base class needs to be
441 * registers on its own before it can be used as base class.
443 * @tparam Base Type of base class (Base as used in Ghost<BasePtr>)
446 * Ghost<MyBasePtr>::init("MyBase");
447 * Ghost<MyClassPtr>::init("MyClass")
448 * .bases<MyBasePtr>();
452 typename boost::disable_if
454 boost::is_base_of<GhostMetadata, Base>,
461 boost::is_base_of<typename Ghost<Base>::raw_type, raw_type>::value
464 return bases< Ghost<Base> >();
468 * Register an existing Nasal class/hash as base class for this ghost.
470 * @param parent Nasal hash/class
472 Ghost& bases(const naRef& parent)
474 addNasalBase(parent);
479 * Register a member variable by passing a getter and/or setter method.
481 * @param field Name of member
482 * @param getter Getter for variable
483 * @param setter Setter for variable (Pass 0 to prevent write access)
486 template<class Ret, class Param>
487 Ghost& member( const std::string& field,
488 Ret (raw_type::*getter)() const,
489 void (raw_type::*setter)(Param) )
491 return member(field, to_getter(getter), to_setter(setter));
494 template<class Param>
495 Ghost& member( const std::string& field,
496 const getter_t& getter,
497 void (raw_type::*setter)(Param) )
499 return member(field, getter, to_setter(setter));
503 Ghost& member( const std::string& field,
504 Ret (raw_type::*getter)() const,
505 const setter_t& setter )
507 return member(field, to_getter(getter), setter);
511 * Register a read only member variable.
513 * @param field Name of member
514 * @param getter Getter for variable
517 Ghost& member( const std::string& field,
518 Ret (raw_type::*getter)() const )
520 return member(field, to_getter(getter), setter_t());
523 Ghost& member( const std::string& field,
524 naRef (*getter)(const raw_type&, naContext) )
526 return member(field, getter_t(getter), setter_t());
529 Ghost& member( const std::string& field,
530 naRef (*getter)(raw_type&, naContext) )
532 return member(field, getter_t(getter), setter_t());
536 * Register a write only member variable.
538 * @param field Name of member
539 * @param setter Setter for variable
542 Ghost& member( const std::string& field,
543 void (raw_type::*setter)(Var) )
545 return member(field, getter_t(), to_setter(setter));
548 Ghost& member( const std::string& field,
549 void (*setter)(raw_type&, naContext, naRef) )
551 return member(field, getter_t(), setter_t(setter));
554 Ghost& member( const std::string& field,
555 const setter_t& setter )
557 return member(field, getter_t(), setter);
561 * Register a member variable by passing a getter and/or setter method.
563 * @param field Name of member
564 * @param getter Getter for variable
565 * @param setter Setter for variable (Pass empty to prevent write access)
568 Ghost& member( const std::string& field,
569 const getter_t& getter,
570 const setter_t& setter = setter_t() )
572 if( !getter.empty() || !setter.empty() )
573 _members[field] = member_t(getter, setter);
579 "Member '" << field << "' requires a getter or setter"
585 * Register a function which is called upon retrieving an unknown member
588 Ghost& _get(const fallback_getter_t& getter)
590 _fallback_getter = getter;
595 * Register a function which is called upon retrieving an unknown member
596 * of this ghost, and convert it to the given @a Param type.
598 template<class Param>
599 Ghost& _get( const boost::function<bool ( raw_type&,
603 return _get(boost::bind(
604 convert_param_invoker<Param>, getter, _1, _2, _3, _4
609 * Register a method which is called upon retrieving an unknown member of
616 * bool getMember( const std::string& key,
617 * std::string& value_out ) const;
620 * Ghost<MyClassPtr>::init("Test")
621 * ._get(&MyClass::getMember);
624 template<class Param>
625 Ghost& _get(bool (raw_type::*getter)(const std::string&, Param&) const)
628 boost::function<bool (raw_type&, const std::string&, Param&)>(getter)
633 * Register a method which is called upon retrieving an unknown member of
640 * bool getMember( naContext c,
641 * const std::string& key,
642 * naRef& value_out );
645 * Ghost<MyClassPtr>::init("Test")
646 * ._get(&MyClass::getMember);
649 Ghost& _get(bool (raw_type::*getter)( naContext,
653 return _get( fallback_getter_t(getter) );
657 * Register a function which is called upon setting an unknown member of
660 Ghost& _set(const fallback_setter_t& setter)
662 _fallback_setter = setter;
667 * Register a function which is called upon setting an unknown member of
668 * this ghost, and convert it to the given @a Param type.
670 template<class Param>
671 Ghost& _set(const boost::function<bool ( raw_type&,
675 // Setter signature: bool( raw_type&,
677 // const std::string&,
679 return _set(boost::bind(
683 boost::bind(from_nasal_ptr<Param>::get(), _2, _4)
688 * Register a method which is called upon setting an unknown member of
695 * bool setMember( const std::string& key,
696 * const std::string& value );
699 * Ghost<MyClassPtr>::init("Test")
700 * ._set(&MyClass::setMember);
703 template<class Param>
704 Ghost& _set(bool (raw_type::*setter)(const std::string&, Param))
707 boost::function<bool (raw_type&, const std::string&, Param)>(setter)
712 * Register a method which is called upon setting an unknown member of
719 * bool setMember( naContext c,
720 * const std::string& key,
724 * Ghost<MyClassPtr>::init("Test")
725 * ._set(&MyClass::setMember);
728 Ghost& _set(bool (raw_type::*setter)( naContext,
732 return _set( fallback_setter_t(setter) );
736 * Register anything that accepts an object instance and a
737 * nasal::CallContext and returns naRef as method.
743 * naRef myMethod(const nasal::CallContext& ctx);
746 * Ghost<MyClassPtr>::init("Test")
747 * .method("myMethod", &MyClass::myMethod);
750 Ghost& method(const std::string& name, const method_t& func)
752 _members[name].func = new MethodHolder(func);
757 * Register anything that accepts an object instance and a
758 * nasal::CallContext whith automatic conversion of the return type to
763 * void doIt(const MyClass& c, const nasal::CallContext& ctx);
765 * Ghost<MyClassPtr>::init("Test")
766 * .method("doIt", &doIt);
772 const std::string& name,
773 const boost::function<Ret (raw_type&, const CallContext&)>& func
776 return method(name, boost::bind(method_invoker<Ret>, func, _1, _2));
779 // Build dependency for CMake, gcc, etc.
780 #define SG_DONT_DO_ANYTHING
781 # include <simgear/nasal/cppbind/detail/functor_templates.hxx>
782 #undef SG_DONT_DO_ANYTHING
784 #define BOOST_PP_ITERATION_LIMITS (0, 9)
785 #define BOOST_PP_FILENAME_1 <simgear/nasal/cppbind/detail/functor_templates.hxx>
786 #include BOOST_PP_ITERATE()
789 * Create a shared pointer on the heap to handle the reference counting
790 * for the passed shared pointer while it is used in Nasal space.
792 template<class RefType>
794 typename boost::enable_if_c<
795 boost::is_same<RefType, strong_ref>::value
796 || boost::is_same<RefType, weak_ref>::value,
799 makeGhost(naContext c, RefType const& ref_ptr)
801 strong_ref ref(ref_ptr);
802 raw_type* ptr = get_pointer(ref_ptr);
806 // We are wrapping shared pointers to already existing objects which
807 // will then be hold be a new shared pointer. We therefore have to
808 // check for the dynamic type of the object as it might differ from
809 // the passed static type.
810 naGhostType* ghost_type =
811 getTypeFor<Ghost>(ptr, shared_ptr_traits<RefType>::is_strong::value);
816 return naNewGhost2(c, ghost_type, new RefType(ref_ptr));
820 * Convert Nasal object to C++ object. To get a valid object the passed
821 * Nasal objects has to be derived class of the target class (Either
822 * derived in C++ or in Nasal using a 'parents' vector)
824 template<class RefType>
826 typename boost::enable_if_c<
827 boost::is_same<RefType, strong_ref>::value
828 || boost::is_same<RefType, weak_ref>::value,
831 fromNasal(naContext c, naRef me)
833 bool is_weak = false;
835 // Check if it's a ghost and if it can be converted
836 if( isBaseOf(naGhost_type(me), is_weak) )
838 void* ghost = naGhost_ptr(me);
839 return is_weak ? getPtr<RefType, true>(ghost)
840 : getPtr<RefType, false>(ghost);
843 // Now if it is derived from a ghost (hash with ghost in parent vector)
844 else if( naIsHash(me) )
846 naRef na_parents = naHash_cget(me, const_cast<char*>("parents"));
847 if( !naIsVector(na_parents) )
850 typedef std::vector<naRef> naRefs;
851 naRefs parents = from_nasal<naRefs>(c, na_parents);
852 for( naRefs::const_iterator parent = parents.begin();
853 parent != parents.end();
856 RefType ptr = fromNasal<RefType>(c, *parent);
857 if( get_pointer(ptr) )
865 static bool isBaseOf(naRef obj)
868 return isBaseOf(naGhost_type(obj), is_weak);
876 static naGhostType _ghost_type_strong, //!< Stored as shared pointer
877 _ghost_type_weak; //!< Stored as weak shared pointer
879 typedef naGhostType* (*type_checker_t)(const raw_type*, bool);
880 typedef std::vector<type_checker_t> DerivedList;
881 DerivedList _derived_types;
883 static bool isBaseOf(naGhostType* ghost_type, bool& is_weak)
885 if( !ghost_type || !getSingletonPtr() )
888 return getSingletonPtr()->GhostMetadata::isBaseOf(ghost_type, is_weak);
891 static bool isBaseOf(naRef obj, bool& is_weak)
893 return isBaseOf(naGhost_type(obj), is_weak);
896 template<class RefPtr, bool is_weak>
898 typename boost::enable_if_c<
905 return RefPtr(*static_cast<strong_ref*>(ptr));
910 template<class RefPtr, bool is_weak>
912 typename boost::enable_if_c<
913 is_weak && supports_weak_ref<T>::value,
919 return RefPtr(*static_cast<weak_ref*>(ptr));
924 template<class RefPtr, bool is_weak>
926 typename boost::enable_if_c<
927 is_weak && !supports_weak_ref<T>::value,
935 void addDerived( const internal::GhostMetadata* derived_meta,
936 type_checker_t derived_type_checker )
938 GhostMetadata::addDerived(derived_meta);
939 _derived_types.push_back(derived_type_checker);
942 template<class BaseGhost>
944 typename boost::enable_if
945 < boost::is_polymorphic<typename BaseGhost::raw_type>,
948 getTypeFor(const typename BaseGhost::raw_type* base, bool strong)
950 // Check first if passed pointer can by converted to instance of class
953 < typename BaseGhost::raw_type,
954 typename Ghost::raw_type
956 && dynamic_cast<const typename Ghost::raw_type*>(base) != base )
959 if( !getSingletonPtr() )
965 "Ghost::getTypeFor: can not get type for unregistered ghost"
970 // Now check if we can further downcast to one of our derived classes.
971 for( typename DerivedList::reverse_iterator
972 derived = getSingletonPtr()->_derived_types.rbegin();
973 derived != getSingletonPtr()->_derived_types.rend();
976 naGhostType* ghost_type =
978 static_cast<const typename Ghost::raw_type*>(base),
986 // If base is not an instance of any derived class, this class has to
987 // be the dynamic type.
989 ? &_ghost_type_strong
993 template<class BaseGhost>
995 typename boost::disable_if
996 < boost::is_polymorphic<typename BaseGhost::raw_type>,
999 getTypeFor(const typename BaseGhost::raw_type* base, bool strong)
1001 // For non polymorphic classes there is no possibility to get the actual
1002 // dynamic type, therefore we can only use its static type.
1004 ? &BaseGhost::_ghost_type_strong
1005 : &BaseGhost::_ghost_type_weak;
1008 static Ghost* getSingletonPtr()
1010 return getSingletonHolder().get();
1013 static raw_type& requireObject(naContext c, naRef me)
1015 raw_type* obj = get_pointer( fromNasal<strong_ref>(c, me) );
1019 naGhostType* ghost_type = naGhost_type(me);
1023 "method called on object of wrong type: is '%s' expected '%s'",
1024 naIsNil(me) ? "nil" : (ghost_type ? ghost_type->name : "unknown"),
1025 _ghost_type_strong.name
1033 getter_t to_getter(Ret (raw_type::*getter)() const)
1035 typedef typename boost::call_traits<Ret>::param_type param_type;
1036 naRef(*to_nasal_)(naContext, param_type) = &to_nasal;
1038 // Getter signature: naRef(raw_type&, naContext)
1043 boost::bind(getter, _1)
1047 template<class Param>
1048 setter_t to_setter(void (raw_type::*setter)(Param))
1050 // Setter signature: void(raw_type&, naContext, naRef)
1055 boost::bind(from_nasal_ptr<Param>::get(), _2, _3)
1060 * Invoke a method which writes the converted parameter to a reference
1062 template<class Param>
1064 bool convert_param_invoker
1066 const boost::function<bool ( raw_type&,
1071 const std::string& key,
1076 if( !func(obj, key, p) )
1079 out = to_nasal(c, p);
1084 * Invoke a method which returns a value and convert it to Nasal.
1088 typename boost::disable_if<boost::is_void<Ret>, naRef>::type
1091 const boost::function<Ret (raw_type&, const CallContext&)>& func,
1093 const CallContext& ctx
1096 return (*to_nasal_ptr<Ret>::get())(ctx.c, func(obj, ctx));
1100 * Invoke a method which returns void and "convert" it to nil.
1104 typename boost::enable_if<boost::is_void<Ret>, naRef>::type
1107 const boost::function<Ret (raw_type&, const CallContext&)>& func,
1109 const CallContext& ctx
1117 * Extract argument by index from nasal::CallContext and convert to given
1122 typename boost::disable_if<
1123 internal::reduced_is_same<Arg, CallContext>,
1124 typename from_nasal_ptr<Arg>::return_type
1126 arg_from_nasal(const CallContext& ctx, size_t index)
1128 return ctx.requireArg<Arg>(index);
1132 * Specialization to pass through nasal::CallContext.
1136 typename boost::enable_if<
1137 internal::reduced_is_same<Arg, CallContext>,
1138 typename from_nasal_ptr<Arg>::return_type
1140 arg_from_nasal(const CallContext& ctx, size_t)
1142 // Either const CallContext& or CallContext, non-const reference
1143 // does not make sense.
1144 BOOST_STATIC_ASSERT( (!boost::is_same<Arg, CallContext&>::value) );
1148 typedef std::auto_ptr<Ghost> GhostPtr;
1150 fallback_getter_t _fallback_getter;
1151 fallback_setter_t _fallback_setter;
1153 explicit Ghost(const std::string& name):
1154 GhostMetadata( name,
1155 &_ghost_type_strong,
1156 supports_weak_ref<T>::value ? &_ghost_type_weak : NULL )
1158 _ghost_type_strong.destroy = &destroy<strong_ref>;
1159 _ghost_type_strong.name = _name_strong.c_str();
1160 _ghost_type_strong.get_member = &getMember<false>;
1161 _ghost_type_strong.set_member = &setMember<false>;
1163 _ghost_type_weak.destroy = &destroy<weak_ref>;
1164 _ghost_type_weak.name = _name_weak.c_str();
1166 bool can_weak = supports_weak_ref<T>::value;
1167 _ghost_type_weak.get_member = can_weak ? &getMember<true> : 0;
1168 _ghost_type_weak.set_member = can_weak ? &setMember<true> : 0;
1171 static GhostPtr& getSingletonHolder()
1173 static GhostPtr instance;
1177 template<class Type>
1178 static void destroy(void *ptr)
1180 delete static_cast<Type*>(ptr);
1184 * Callback for retrieving a ghost member.
1186 static const char* getMember( naContext c,
1191 const std::string key_str = nasal::from_nasal<std::string>(c, key);
1192 // TODO merge instance parents with static class parents
1193 // if( key_str == "parents" )
1195 // if( getSingletonPtr()->_parents.empty() )
1198 // *out = getSingletonPtr()->getParents(c);
1202 typename MemberMap::iterator member =
1203 getSingletonPtr()->_members.find(key_str);
1205 if( member == getSingletonPtr()->_members.end() )
1207 fallback_getter_t fallback_get = getSingletonPtr()->_fallback_getter;
1209 || !fallback_get(obj, c, key_str, *out) )
1212 else if( member->second.func )
1213 *out = member->second.func->get_naRef(c);
1214 else if( !member->second.getter.empty() )
1215 *out = member->second.getter(obj, c);
1217 return "Read-protected member";
1222 template<bool is_weak>
1223 static const char* getMember( naContext c,
1228 strong_ref const& ptr = getPtr<strong_ref, is_weak>(ghost);
1229 return getMember(c, *get_pointer(ptr), key, out);
1233 * Callback for writing to a ghost member.
1235 static void setMember( naContext c,
1240 const std::string key = nasal::from_nasal<std::string>(c, field);
1241 const MemberMap& members = getSingletonPtr()->_members;
1243 typename MemberMap::const_iterator member = members.find(key);
1244 if( member == members.end() )
1246 fallback_setter_t fallback_set = getSingletonPtr()->_fallback_setter;
1248 naRuntimeError(c, "ghost: No such member: %s", key.c_str());
1249 else if( !fallback_set(obj, c, key, val) )
1250 naRuntimeError(c, "ghost: Failed to write (_set: %s)", key.c_str());
1252 else if( member->second.setter.empty() )
1253 naRuntimeError(c, "ghost: Write protected member: %s", key.c_str());
1254 else if( member->second.func )
1255 naRuntimeError(c, "ghost: Write to function: %s", key.c_str());
1257 member->second.setter(obj, c, val);
1260 template<bool is_weak>
1261 static void setMember( naContext c,
1266 strong_ref const& ptr = getPtr<strong_ref, is_weak>(ghost);
1267 return setMember(c, *get_pointer(ptr), field, val);
1272 naGhostType Ghost<T>::_ghost_type_strong;
1274 naGhostType Ghost<T>::_ghost_type_weak;
1276 } // namespace nasal
1278 // Needs to be outside any namespace to make ADL work
1280 * Convert every shared pointer to a ghost.
1283 typename boost::enable_if<
1284 nasal::internal::has_element_type<
1285 typename nasal::internal::reduced_type<T>::type
1289 to_nasal_helper(naContext c, T ptr)
1291 typedef typename nasal::shared_ptr_traits<T>::strong_ref strong_ref;
1292 return nasal::Ghost<strong_ref>::makeGhost(c, ptr);
1296 * Convert nasal ghosts/hashes to shared pointer (of a ghost).
1299 typename boost::enable_if<
1300 nasal::internal::has_element_type<
1301 typename nasal::internal::reduced_type<T>::type
1305 from_nasal_helper(naContext c, naRef ref, const T*)
1307 typedef typename nasal::shared_ptr_traits<T>::strong_ref strong_ref;
1308 return nasal::Ghost<strong_ref>::template fromNasal<T>(c, ref);
1312 * Convert any pointer to a SGReference based object to a ghost.
1315 typename boost::enable_if_c<
1316 boost::is_base_of<SGReferenced, T>::value
1317 || boost::is_base_of<SGWeakReferenced, T>::value,
1320 to_nasal_helper(naContext c, T* ptr)
1322 return nasal::Ghost<SGSharedPtr<T> >::makeGhost(c, SGSharedPtr<T>(ptr));
1326 * Convert nasal ghosts/hashes to pointer (of a SGReference based ghost).
1329 typename boost::enable_if_c<
1332 typename boost::remove_pointer<T>::type
1334 || boost::is_base_of<
1336 typename boost::remove_pointer<T>::type
1340 from_nasal_helper(naContext c, naRef ref, const T*)
1342 typedef SGSharedPtr<typename boost::remove_pointer<T>::type> TypeRef;
1343 return nasal::Ghost<TypeRef>::template fromNasal<TypeRef>(c, ref).release();
1346 #endif /* SG_NASAL_GHOST_HXX_ */