I feel like I am almost there! I started of trying with TH1D for simplicities sake. The following compiles and runs, but I do not know how to cast the python histogram to the cpp histogram. Here is what I have got:
# distutils: language = c++
# fill_histogram.pyx
from ROOT import AddressOf
import cython
cdef extern from "TH1D.h":# namespace "TH1D":
cdef cppclass TH1D:
TH1D()
int Fill(double)
char* GetName()
def fill_histogram(hist_in):
# hist = AddressOf(hist_in) # <-- Does not work
print "Finished fill_histogram"
import os
import shutil
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
# clean previous build
for root, dirs, files in os.walk(".", topdown=False):
for name in files:
if (name.startswith("fill_histogram")
and not(name.endswith(".pyx") or name.endswith(".pxd"))):
os.remove(os.path.join(root, name))
for name in dirs:
if (name == "build"):
shutil.rmtree(name)
setup(
cmdclass={'build_ext': build_ext},
ext_modules=[Extension(
"fill_histogram", # name of the extension
sources=["fill_histogram.pyx"], # additional source file(s)
language="c++", # generate C++ code
include_dirs=["/home/christian/root/include", ],
library_dirs=["/home/christian/root/lib", ],
libraries=["python2.7", "Core", "Cint", "RIO", "Net", "Hist", "Graf",
"Graf3d", "Gpad", "Tree", "Rint", "Postscript",
"Matrix", "Physics", "MathCore", "Thread",
"pthread", "m", "dl"],
# set complier options here:
extra_compile_args=["-I/home/christian/root/lib"],
)])
# main.py
# do
# $ export LD_LIBRARY_PATH=path/to/root/lib
# befor running with:
# $ python main.py
from fill_histogram import fill_histogram
from ROOT import TH1F, AddressOf
hist = TH1D()
ptr = AddressOf(hist) # of type PyLongBuffer or somthing
fill_histogram(hist)
The problem now is in the fill_histogram.pyx (first snippet).
How do make the cython histogram ´hist´ point to the python object ´hist_in´? The commented line
hist = AddressOf(hist_in)
did not work. Nor the cython version of it called cython.address()
Any hints? I think getting those loops into pure C++ code (via cython) would potentially deliver a massive speed up, or am I mistaken?