[C++-sig] Re: Exposing C++ objects to Python at runtime

Daniel Wallin dalwan01 at student.umu.se
Wed Nov 26 11:44:37 CET 2003


Raoul Gough wrote:
> David Abrahams <dave at boost-consulting.com> writes:
> 
> 
>>Raoul Gough <RaoulGough at yahoo.co.uk> writes:
>>
>>
>>>David Abrahams <dave at boost-consulting.com> writes:
> 
> [snip]
> 
>>>>I've been trying to say that you you *can*, in principle, still do
>>>>this with a single ScriptEngine type, so that registration code gets
>>>>compiled once, scripting-language-independently.
>>>
>>>Given a certain amount of wrapper code to set up a "function
>>>descriptor" object, I assume.
>>
>>Yup.
> 
> 
> The only difficulty I've thought of would be handling return values.
> For instance, somewhere you have to have a conversion from the C++
> return type to a PyObject * (for the Python engine) or the
> corresponding type for different engines. Maybe a double-dispatch
> would handle this, meaning a certain amount of scripting language
> dependant code in the function descriptor base class?

I thought it would just work like:

   PyObject* python_function_wrapper()
   {
       function& fn = /* something */;

       const type_info* args = fn.arg_types();

       void** storage_table = /* something */;

       for (int i = 0; i < fn.arity(); ++i)
       {
           void* storage = allocate_storage_for_converter(args[i]);
           perform_conversion(args[i], i, storage, py_args);
           storage_table[i] = storage;
       }

       void* result_storage = allocate_storage_for_converter(
           fn.result_type()
       );

       fn.invoke(storage_table, result_storage);

       return perform_result_conversion(
           fn.result_type()
         , result_storage
       );
   }

and function::invoke, simplified, would just do..

   void function::invoke(void* const* args_storage, void* result_storage)
   {
       new (result_storage) ResultType(
           m_fn(
               static_cast<A0*>(args_storage[0])
             , static_cast<A1*>(args_storage[1])
             , etc..
           )
       );
   }

I guess you'd also need a virtual tail call that can destroy the
result..

Of course, the converter lookup would be done at init time and stored.

-- 
Daniel Wallin





More information about the Cplusplus-sig mailing list