Re: [ROOT] trying to write a TClonesArray

From: Rene Brun (Rene.Brun@cern.ch)
Date: Wed Nov 13 2002 - 14:32:54 MET


When writing the TClonesArray, use the option kSingleKey,
otherwise each entry in the TClonesArray becomes a separate key.
See your file modified below

Rene Brun

void write_lv() {

TFile tf("test_lv.root","recreate");
TClonesArray clarr("TLorentzVector",5);
TLorentzVector* lv = new (clarr[0]) TLorentzVector();
lv->SetPxPyPzE(1,2,3,4);

cout << "storing a lorentz vec with a mas of "<<lv->M() << endl;
cout << "momentum: ("<<lv->Px()<< ", "<< lv->Py() << ", "
     << lv->Pz() << " )"<<endl;
cout << "array has "<< clarr.GetEntries()<<" entries"<<endl;

clarr->Write("an_array",TObject::kSingleKey);
tf.Close();
}

void read_lv() {
   TFile tf("test_lv.root");
   TClonesArray* arr = (TClonesArray*)tf.Get("an_array");
   printf("entries = %d\n",arr->GetEntries());
}

void lv() {
   gSystem->Load("libPhysics");
   write_lv();
   read_lv();
}

On Wed, 13 Nov 2002, Paul Balm wrote:

> Hello,
> 
> I'm trying to write a TClonesArray containing one TLorentzVector to a 
> file and read it back. To write the file, I use this function:
> 
> void write_lv() {
> 
> TFile tf("test_lv.root","recreate");
> TClonesArray clarr("TLorentzVector",5);
> TLorentzVector* lv = new (clarr[0]) TLorentzVector();
> lv->SetPxPyPzE(1,2,3,4);
> 
> cout << "storing a lorentz vec with a mas of "<<lv->M() << endl;
> cout << "momentum: ("<<lv->Px()<< ", "<< lv->Py() << ", "
>      << lv->Pz() << " )"<<endl;
> cout << "array has "<< clarr.GetEntries()<<" entries"<<endl;
> 
> clarr->Write("an_array");
> tf.Close();
> }
> 
> Then I start new root session, open the file, and try to read the 
> TClonesArray:
> 
> root [0] TFile tf("test_lv.root")
> root [1] tf.ls()
> TFile**         test_lv.root
>  TFile*         test_lv.root
>   KEY: TLorentzVector   an_array;1      A four vector with (-,-,-,+) metric
> root [2] TClonesArray* arr = tf.Get("an_array")
> root [3] arr->GetEntries()
> 
>  *** Break *** segmentation violation
> Root >
> root [4] arr
> (class TClonesArray*)0x8979720
> 
> So I didn't get a null pointer, but using it as a TClonesArray, e.g. by 
> calling GetEntries() on it, doesn't work. Also, from the TFile::ls() 
> output, you could already tell that what has been written is a 
> TLorentzVector, and not a TClonesArray. And indeed I can use the pointer 
> I get from the file if I interpret it as a TLorentzVector:
> 
> root [7] TLorentzVector* lv2 = tf.Get("an_array")
> root [8] lv2->M()
> (const Double_t)1.41421356237309515e+00
> 
> This number matches what I expect from what I wrote (sqrt(2)).
> 
> This is root 3.03/09 on Linux RH6. Does anyone have any idea what is 
> going wrong?
> Thanks!
> 
> Paul Balm
> 
> 



This archive was generated by hypermail 2b29 : Sat Jan 04 2003 - 23:51:17 MET