[C++-sig] void* cast to a specific type based on string name
David Abrahams
dave at boostpro.com
Sun Oct 12 21:08:14 CEST 2008
on Mon Oct 06 2008, "Renato Araujo" <renatox-AT-gmail.com> wrote:
> Hi,
>
> for this case I would like to know if is possible create a python
> object based on string name like that:
>
>
> void call_Pyfunction(int argc, char **types, void **args,
> boost::python::object *callbak)
> {
> boost::python::list pyArgs;
> for (int i=0; i <= count; i++)
> {
> //in types I have the typenames: {"int", "string", "MyObject", ....}
> boost::python::object o(types[i], args[i]);
> pyArgs.append(o);
> }
> callback(pyArgs);
> }
Sure, just build a map from type names to conversion functions:
std::map<std::string, python::object(*)(void*)> m;
template <class T>
python::object void_ptr_to_python(void* p)
{
return python::object(*(T*)p);
}
m["int"] = &void_ptr_to_python<int>;
m["string"] = &void_ptr_to_python<std::string>;
m["MyObject"] = &void_ptr_to_python<MyObject>;
Then,
m[types[i]](args[i])
will do the trick.
--
Dave Abrahams
BoostPro Computing
http://www.boostpro.com
More information about the Cplusplus-sig
mailing list