Reading user-defined class back from a file

Hello,

I created my own class ‘MyClass’ and stored and instance of it in a TFile. I have no problem reading the class back from the file in a standalone compiled C++ program. But an interactive ROOT session crashes when I try to include the class header. What would be the correct way to read a user-defined class back from a TFile?

I’m using ROOT 5.24/00b on Linux.

The attached tar.gz file includes a set of files to demonstrate what I mean:

  • after unpacking, a simple ‘make’ should compile the standalone code (creates an executable ‘main’ and and executable ‘read’)
  • run ‘main’ to create a ROOT file which contains instances of ‘MyClass’ as branches of a tree and also as a single instance saved in the TFile.
  • run ‘read’ to read back the contents from the file created by ‘main’
  • now run ‘read.C’ as an interpreted macro in ROOT. How can I read back the object ‘MyClass’?

Thank you for your help,
Jochen
classtest.tar.gz (1.54 KB)

Hi,

you have to create a shared lib with your MyClass and the dictionary. Then in ROOT you’ve to first load this shared library and all is fine. On MacOS do:

g++ -dynamiclib -single_module -undefined dynamic_lookup -o libMyClass.so MyClass.o MyClassdict.o

or

g++ -shared -o libMyClass.so MyClass.o MyClassdict.o

on Linux. Then do:

root
gSystem->Load(“libMyClass.so”)
.x read.C

Cheers, Fons.

I had to recompile the code with the compiler option -fPIC, and now everything is working.

Thanks!
Jochen

Yep, -fPIC is default on MacOS X, where I tried.

Cheers, Fons.