Branching array of char in ttree

Gabriel,

not exactly: CINT saves you by allocating a larger buffer for the string variable that you allocate, and probably initializes it to \0, or what you did in the C++ macro would not have worked (try compiling it, and see it crash at runtime in several places: the assignments beyond the empty string bounds as well as in the print/scan).

In python, you get exactly what you asked for: a character array. That is not a string. You can get the same behavior by creating a larger buffer, and then being careful about ‘\0’ as you are in the C++ macro that you posted. Or, you can use a smaller array, but then you will still need to take care that the array address may change when appending (if you don’t allocate enough memory to start with). Thus, you should reset the branch address every time (i.e. t.SetBranchAddress(‘s’,s) ) before calling Fill().

Something like:[code]t=TTree(‘t’, ‘’)
s=array(‘c’, ‘ab\0’)
t.Branch(‘s’,s,‘s/C’)
t.Fill()
s.pop()
s.extend(‘c\0’)
t.SetBranchAddress(‘s’,s)
t.Fill()

remove not last (which is ‘\0’), but one-but last

s.remove(s[-2])
s.remove(s[-2])
t.SetBranchAddress(‘s’,s)
t.Fill()

t.Scan() [/code]
Alternatively, you can work with a pythonize character buffer, that behaves close to CINT-style:[code]gROOT.ProcessLine( “struct MyStringBuf { char s[256]; };” )
s = MyStringBuf();

t=TTree(‘t’, ‘’)
t.Branch(‘s’,AddressOf(s,‘s’),‘s/C’)
s.s = ‘ab’
t.Fill()

append 1

s.s += ‘c’
t.Fill()

pop 2 by slicing

s.s = s.s[:-2]
t.Fill()

t.Scan()[/code]
In PyROOT, the conversions of string to char-array (and vice versa) take care of the ‘\0’ for you.

HTH,
Wim