Source

mana-core-storegatebindings / src / StoreGatePyExt.cxx

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
// Hide this #include from checkreq so that it doesn't keep giving us warnings.
#define PYTHON_INC "Python.h"
#include PYTHON_INC

#include "StoreGateBindingsDict.h"
#include "SGTools/DataBucketBase.h"
#include "GaudiKernel/Bootstrap.h"
#include "GaudiKernel/DataObject.h"
#include "AthenaKernel/IClassIDSvc.h"

// Reflex includes
#include "Reflex/Type.h"
#include "Reflex/Object.h"

// ROOT includes
#include "TClass.h"
#include "TClassRef.h"
#include "TROOT.h"
#include "Api.h"

#include <string>

// temporaryly duplicate PyROOT's API...
// Wim will fix that up

namespace PyROOT {

class ObjectProxy {
public:
  enum EFlags { kNone = 0x0, kIsOwner = 0x0001, kIsReference = 0x0002 };

  TClass* ObjectIsA() const
  {
    return fClass.GetClass();                        // may return null
  }

  void* GetObject() const
  {
    if ( fObject && ( fFlags & kIsReference ) )
      return *(reinterpret_cast< void** >( const_cast< void* >( fObject ) ));
    else
      return const_cast< void* >( fObject );        // may be null
  }

  void HoldOn() { fFlags |= kIsOwner; }

  PyObject_HEAD
  void*     fObject;
  TClassRef fClass;
  int       fFlags;
};

R__EXTERN PyTypeObject ObjectProxy_Type;

template< typename T >
inline Bool_t ObjectProxy_Check( T* object )
{
  return object && PyObject_TypeCheck( object, &ObjectProxy_Type );
}

PyObject* BindRootObjectNoCast( void* object, TClass* klass, Bool_t isRef = kFALSE );
PyObject* BindRootObject( void* object, TClass* klass, Bool_t isRef = kFALSE );

union TParameter;

class TConverter {
public:
  virtual ~TConverter() {}

public:
  virtual Bool_t SetArg( PyObject*, TParameter&, G__CallFunc* = 0 ) = 0;
  virtual PyObject* FromMemory( void* address );
  virtual Bool_t ToMemory( PyObject* value, void* address );
};

TConverter* CreateConverter( const std::string& fullType, Long_t user = -1 );

class PyCallable;

R__EXTERN PyTypeObject MethodProxy_Type;

struct MethodInfo_t;

class MethodProxy
{
public:
  typedef std::map< Long_t, Int_t >  DispatchMap_t;
  typedef std::vector< PyCallable* > Methods_t;

  void Set( const std::string& name, std::vector< PyCallable* >& methods );
  const std::string& GetName() const;

public:               // public, as the python C-API works with C structs
  PyObject_HEAD
  ObjectProxy*   fSelf;        // The instance it is bound to, or NULL
  MethodInfo_t*  fMethodInfo;
};

MethodProxy* MethodProxy_New(
         const std::string& name, std::vector< PyCallable* >& methods )
{
  MethodProxy* pymeth = (MethodProxy*)MethodProxy_Type.tp_new( &MethodProxy_Type, 0, 0 );
  pymeth->Set( name, methods );
  return pymeth;
}

MethodProxy* MethodProxy_New( const std::string& name, PyCallable* method )
{
  std::vector< PyCallable* > p;
  p.push_back( method );
  return MethodProxy_New( name, p );
}



struct MethodInfo_t {
  std::string                 fName;
  MethodProxy::DispatchMap_t  fDispatchMap;
  MethodProxy::Methods_t      fMethods;
  std::string                 fDoc;
  Bool_t                      fIsSorted;

  int* fRefCount;
};

const std::string& MethodProxy::GetName() const { return fMethodInfo->fName; }

class PyCallable {
public:
  virtual ~PyCallable() {}

public:
  virtual PyObject* GetSignature() = 0;
  virtual PyObject* GetPrototype() = 0;
  virtual PyObject* GetDocString();
  virtual Int_t GetPriority();

public:
  virtual PyObject* operator()( ObjectProxy* self, PyObject* args, PyObject* kwds ) = 0;
};

} //> namespace PyROOT

namespace SG {

  /**
   * @brief Concrete @c DataBucket that holds the object via a @c void*
   *        and uses the Root dictionary to do conversions.
   *
   * A concrete @c DataBucket instance holds a pointer to an arbitrary
   * object, and is able to further convert it to pointers to other
   * types related by inheritance.  This variant is used for PyAthena,
   * where don't have the type available at compile time and thus cannot
   * use templates.  However, we know that we do have the Root dictionary
   * available for the types, so we can use that information for the
   * conversions.
   */
  class PyDataBucket : public DataBucketBase
  {
  public:
    /**
     * @brief Constructor.
     * @param pyObj The (pyroot) object proxy to hold.
     * @param clid The class ID of the wrapped object.
     */
    PyDataBucket( PyROOT::ObjectProxy* pyObj,
		  CLID clid );


    /**
     * @brief Destructor.
     */
    ~PyDataBucket() { Py_DECREF( m_pyObj ); }
    /**
     * @brief Return the held object.
     */
    virtual void* object() { return m_pyObj->GetObject(); }


    /**
     * @brief Return the contents of the @c DataBucket,
     *        converted to type given by @a clid.  Note that only
     *        derived->base conversions are allowed here.
     * @param clid The class ID to which to convert.
     */
    virtual void* cast (CLID clid) const;


    /**
     * @brief Return the contents of the @c DataBucket,
     *        converted to type given by @c std::type_info.  Note that only
     *        derived->base conversions are allowed here.
     * @param tinfo The @c std::type_info of the type to which to convert.
     */
    virtual void* cast (const std::type_info& tinfo) const;

    /**
     * @brief Retrieve reference to class definition structure
     */
    virtual const CLID& clID() const { return m_clid; }

    /**
     * @brief Return a new @c DataBucket whose payload has been cloned from the
     *        original one.
     */
    virtual SG::PyDataBucket* clone() const;

  private:
    /// Pointer to the held pyroot object.
    PyROOT::ObjectProxy* m_pyObj;

    /// The class ID of the wrapped object.
    CLID m_clid;

    /// Pointer to the @ IClassIDSvc to be able to cast objects based
    /// the @a clid.
    static IClassIDSvc* s_clidSvc;

    /// Access (and initialize) the pointer to the @c IClassIDSvc
    static IClassIDSvc* clidSvc();
  };
}

PyObject* AthenaInternal::retrieveObjectFromStore(
      StoreGateSvc* store, PyObject* tp, PyObject* key, void*& res )
{
   static IClassIDSvc* s_clidsvc = 0;

// unlikely to happen, but checking is cheap
   if ( ! store ) {
      PyErr_SetString( PyExc_RuntimeError, "no store available, is Athena initialized?" );
      return 0;
   }

// expect a type or type name and an optional string key
   PyObject* pyname = 0;
   if ( ! PyType_Check( tp ) ) {
      if ( ! PyString_Check( tp ) ) {
         PyErr_SetString( PyExc_TypeError, "retrieve() argument 1 must be type or class name" );
         return 0;
      } else {
         Py_INCREF( tp );
         pyname = tp;
      }
   } else {
      pyname = PyObject_GetAttrString( tp, (char*)"__name__" );
      if ( pyname && ! PyString_Check( pyname ) ) {
         PyObject* pystr = PyObject_Str( pyname );
         if ( pystr ) {
            Py_DECREF( pyname );
            pyname = pystr;
         }
      }

      if ( PyErr_Occurred() )
         return 0;
   }

   if ( key != Py_None && ! PyString_Check( key ) ) {
      PyErr_SetString( PyExc_TypeError, "retrieve() argument 2 must be string key" );
      return 0;
   }

// retrieve CLID corresponding to the request
   if ( ! s_clidsvc ) {
      StatusCode sc = Gaudi::svcLocator()->getService( "ClassIDSvc", (IService*&)s_clidsvc );
      if ( sc.isFailure() ) {
         PyErr_SetString( PyExc_RuntimeError, "ClassIDSvc does not exist" );
         return 0;
      }
   }

   std::string name = PyString_AS_STRING( pyname );
   CLID id = CLID_NULL;
   StatusCode sc = s_clidsvc->getIDOfTypeName( name, id );
   if ( sc.isFailure() ) {
      PyErr_Format( PyExc_NameError, "ID of %s is unknown", name.c_str() );
      return 0;
   }

   SG::DataProxy* proxy = 0;
   if ( key != Py_None ) {
      std::string skey = PyString_AS_STRING( key );
      proxy = store->proxy( id, skey );
   } else {
      proxy = store->proxy( id );
   }

   if ( ! proxy ) {
      PyErr_Format( PyExc_LookupError, "no proxies for \"%s\"", name.c_str() );
      return 0;
   }

// cast proxy to pointer type if needed (setting on return type is evil hack)
   DataObject* dobj = proxy->accessData();
   if ( ! dobj ) {
      PyErr_Format( PyExc_LookupError, "no such object \"%s\"", name.c_str() );
      return 0;
   }

   DataBucketBase* dbb = dynamic_cast< DataBucketBase* >( dobj );
   if ( ! dbb ) {
      PyErr_SetString( PyExc_TypeError,
         "unexpected kind of DataObject: can not verify final type" );
      return 0;
   }

   CLID realID = dbb->clID();
   if ( id == realID ) {
      res = dbb->object();

      if ( ! res ) {
         PyErr_Format( PyExc_RuntimeError, "found an invalid object" );
         return 0;
      }

   } else {
   // either use CLID BaseInfo<> or Reflex, try both as appropriate
      res = dbb->cast( id );

      if ( ! res ) {
         std::string realName;
         StatusCode sc = s_clidsvc->getTypeNameOfID( realID, name );
         if ( sc.isFailure() ) {
            PyErr_Format( PyExc_TypeError, "actual type of CLID %lu unknown",
                          (long unsigned int)realID );
            return 0;
         }

         const ROOT::Reflex::Type& fromType = ROOT::Reflex::Type::ByName( realName );

         if ( (bool)fromType ) {
            ROOT::Reflex::Object realobj( fromType, dbb->object() );

            const ROOT::Reflex::Type& toType = ROOT::Reflex::Type::ByName( name );
            const ROOT::Reflex::Object& finalobj = fromType.CastObject( toType, realobj );

            res = (void*)finalobj.Address();
         }

      }

      if ( ! res ) {
         PyErr_SetString( PyExc_TypeError, "cast to requested type failed" );
         return 0;
      }

   }

   Py_INCREF( Py_None );
   return Py_None;
}

PyObject* 
AthenaInternal::recordObjectToStore( StoreGateSvc* store, 
				     PyObject* obj, PyObject* key )
{
  static IClassIDSvc* s_clidsvc = 0;

  // unlikely to happen, but checking is cheap
  if ( !store ) {
    PyErr_SetString( PyExc_RuntimeError, "no store available, is Athena initialized?" );
    return 0;
  }
  
  // expect a type or type name
  PyObject* tp = PyObject_GetAttrString( obj, (char*)"__class__" );
  if ( ! PyType_Check( tp ) ) {
      PyErr_SetString( PyExc_RuntimeError, 
		       "could not retrieve type of object" );
      return 0;
  }
  PyObject* pyname = PyObject_GetAttrString( tp, (char*)"__name__" );
  if ( pyname && ! PyString_Check( pyname ) ) {
    PyObject* pystr = PyObject_Str( pyname );
    if ( pystr ) {
      Py_DECREF( pyname );
      pyname = pystr;
    }
  }
  if ( PyErr_Occurred() )
    return 0;
    
  if ( ! PyString_Check( key ) ) {
    PyErr_SetString( PyExc_TypeError, 
		     "record() argument 2 must be string key" );
    return 0;
  }
  
  // retrieve CLID corresponding to the request
  if ( ! s_clidsvc ) {
    StatusCode sc = Gaudi::svcLocator()->getService( "ClassIDSvc", (IService*&)s_clidsvc );
    if ( sc.isFailure() ) {
      PyErr_SetString( PyExc_RuntimeError, "ClassIDSvc does not exist" );
      return 0;
    }
  }
  
  std::string name = PyString_AS_STRING( pyname );
  CLID id = CLID_NULL;
  StatusCode sc = s_clidsvc->getIDOfTypeName( name, id );
  if ( sc.isFailure() ) {
    PyErr_Format( PyExc_NameError, "ID of %s is unknown", name.c_str() );
    return 0;
  }
  
  PyROOT::ObjectProxy* pyRootObj = (PyROOT::ObjectProxy*)obj;
  DataObject* dataObj = new SG::PyDataBucket( pyRootObj, id );
  static bool allowMods = true;
  if ( !store->typeless_record( dataObj, PyString_AS_STRING(key),
				pyRootObj->GetObject(),
				allowMods ).isSuccess() ) {
      PyErr_SetString( PyExc_RuntimeError, "Failed to record py-dataobject" );
      return 0;
  }

  Py_INCREF( Py_None );
  return Py_None;
}

//
namespace SG {
  IClassIDSvc* PyDataBucket::s_clidSvc = 0;
  IClassIDSvc* PyDataBucket::clidSvc()
  {
    if ( 0 == s_clidSvc ) {
      Gaudi::svcLocator()->getService( "ClassIDSvc", 
				       (IService*&)s_clidSvc ).ignore();
    }
    return s_clidSvc;
  }

  PyDataBucket::PyDataBucket( PyROOT::ObjectProxy* pyObj,
			      CLID clid ) :
    DataBucketBase(),
    m_pyObj( pyObj ),
    m_clid ( clid  )
  {
    // prevent Python from sweeping the rug under our feet
    Py_INCREF( pyObj );
  }

  void* PyDataBucket::cast( CLID clid ) const
  {
    // if requested type is same than myself ==> no conversion needed
    if ( clid == m_clid ) {
      return m_pyObj->GetObject();
    }

    std::string clidTypeName;
    StatusCode sc = clidSvc()->getTypeNameOfID(clid, clidTypeName);
    if ( sc.isFailure() ) {
      PyErr_Format( PyExc_TypeError, "actual type of CLID %lu unknown",
		    (long unsigned int)clid );
      return 0;
    }

    // Create a converter for that type
    PyROOT::TConverter* pcnv = PyROOT::CreateConverter( clidTypeName );
    void* address = m_pyObj->GetObject();
    PyObject* value = pcnv->FromMemory(&address);
    delete pcnv;

    if ( PyROOT::ObjectProxy_Check(value) ) {
      return ((PyROOT::ObjectProxy*)value)->GetObject();
    }
    Py_XDECREF(value);
    PyErr_Format( PyExc_TypeError, 
		  "Could not convert to %s", clidTypeName.c_str() );
    return 0;
  }

  void* PyDataBucket::cast( const std::type_info& tinfo ) const
  {
    // if requested type is same than myself ==> no conversion needed
    if ( tinfo == *(m_pyObj->fClass->GetTypeInfo()) ) {
      return m_pyObj->GetObject();
    }

    // Create a converter for that type
    PyROOT::TConverter* pcnv = PyROOT::CreateConverter( tinfo.name() );
    void* address = m_pyObj->GetObject();
    PyObject* value = pcnv->FromMemory(&address);
    delete pcnv;

    if ( PyROOT::ObjectProxy_Check(value) ) {
      return ((PyROOT::ObjectProxy*)value)->GetObject();
    }
    Py_XDECREF(value);
    PyErr_Format( PyExc_TypeError, 
		  "Could not convert to %s", tinfo.name() );
    return 0;
  }

  PyDataBucket* PyDataBucket::clone() const
  { 
    PyErr_SetString
      ( PyExc_RuntimeError, 
	"SG::PyDataBucket::clone() is not meant to be called (yet)" );
    std::abort();
    return 0;
//     new SG::PyDataBucket( m_type, copy<>(m_pyObj), m_clid );
   }

} //< end namespace SG
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.