Interpret string [Was: Re: ]

From: Christian Holm Christensen <cholm_at_nbi.dk>
Date: Tue, 14 Aug 2007 17:50:37 +0200


Hi Andrea

Please provide a "subject" - thanks.

On Tue, 2007-08-14 at 15:30 +0200, Andrea Massironi wrote:
> Dear Rooters,
> Is it possible to execute a Cint script contained in a string?
> I'd like to do something like this:
>
> std::string instruction = "int a=1";
>
> and then something to "execute instruction"

   gROOT->ProcessLine("int a = 1; ");    

For example, in a script:

   void foo()
   {

     gROOT->ProcessLine("int a = 1; ");
     std::cout << a << std::endl;

   }

which will output "1". If you try to compile the above, it won't work. "a" is not declared, so the compiler will fail in the `cout'-line. On the other hand

   void foo()
   {

     gROOT->ProcessLine("int a = 1; ");
     gROOT->ProcessLine("std::cout << a << std::endl;");
   }  

can be compiled, and does output "1". What this means, is that the variables, etc. declared in the 'interpreter' scope is not visible in the 'compiled' scope, and that all 'interpreter' variables, etc. are global (at least if declared this way). Note, also, that if you need to change a variable in the interpreter, declared or otherwise manipulated in the compiled code, you need to make a dictionary for it. The best option is to make a static `getter' or a singleton:

  class Singleton
  {
  public:
    Singleton& Instance() {

       if (!_instance) {
         _lock.Lock(); // Double check, to prevent race-conditions. 
         if (!_instance) _instance = new Singleton;
         _lock.Unlock();
       }
       return *_instance;

    }
    ~Singleton() { /* maybe do Phenix deallocation? */ }     void DoSomething() { ... }
  protected:
    Singleton() {}
    Singleton(const Singleton&) {}
    Singleton& operator=(const Singleton&) { return *this; }     static Singleton* _instance;
    static Lock _lock;
  };
  #pragma link C++ class Singleton;
  Singleton* Singleton::_instance = 0;
  ...
  gROOT->ProcesssLine("Singleton::Instance().DoSomething();");

Or, a 'simpler' (but less clean) example

  // Compiled code
  int a = 0;
  #pragma link C++ global a;
  ...
  gROOT->ProcessLine("a = 42");
  std::cout << a << std::endl;   

Yours,

-- 
 ___  |  Christian Holm Christensen 
  |_| |  -------------------------------------------------------------
    | |  Address: Sankt Hansgade 23, 1. th.  Phone:  (+45) 35 35 96 91
     _|           DK-2200 Copenhagen N       Cell:   (+45) 24 61 85 91
    _|            Denmark                    Office: (+45) 353  25 404
 ____|   Email:   cholm_at_nbi.dk               Web:    www.nbi.dk/~cholm
 | |
Received on Tue Aug 14 2007 - 17:50:45 CEST

This archive was generated by hypermail 2.2.0 : Tue Aug 14 2007 - 23:50:02 CEST