def initialise(pkg, lib_file, map_file): pkg_dir = os.path.dirname(__file__) pkg_module = sys.modules[pkg] # # Load the library. # cppyy.add_include_path(pkg_dir + "/include") cppyy.add_include_path(pkg_dir + "/include/bx") cppyy.add_include_path(pkg_dir + "/include/bimg") cppyy.add_include_path(pkg_dir + "/include/bgfx") cppyy.add_include_path(pkg_dir + "/include/imgui") cppyy.add_include_path(pkg_dir + "/include/examples/common") cppyy.load_reflection_info(os.path.join(pkg_dir, lib_file)) # # Load pythonizations # try: pythonization_files = glob.glob(os.path.join(pkg_dir, "**/pythonize*.py"), recursive=True) except TypeError: # versions older than 3.5 do not support 'recursive' # TODO: below is good enough for most cases, but not recursive pythonization_files = glob.glob(os.path.join(pkg_dir, "pythonize*.py")) add_pythonizations(pythonization_files) with open(os.path.join(pkg_dir, map_file), "r") as map_file: files = json.load(map_file) for file in files: add_after_namespaces = [] for child in file["children"]: simple_name = child["name"].split("::")[0] if child["kind"] == "namespace": entity = getattr(cppyy.gbl, simple_name) if getattr(entity, "__module__", None) == "cppyy.gbl": setattr(entity, "__module__", pkg) setattr(pkg_module, simple_name, entity) else: add_after_namespaces.append(child) for child in add_after_namespaces: simple_name = child["name"].split("::")[0] if child["kind"] == "enum": for enum_value in child["enumerations"]: enum_value_name = enum_value["name"] entity = getattr(cppyy.gbl, enum_value_name) setattr(entity, "__module__", pkg + ".ImGui") setattr(pkg_module.ImGui, enum_value_name, entity) elif child["kind"] not in ( "typedef", "function", ) and simple_name.startswith("Im"): entity = getattr(cppyy.gbl, simple_name) setattr(entity, "__module__", pkg + ".ImGui") setattr(pkg_module.ImGui, simple_name, entity)
def test02_crossing_dict(self): """Test availability of all needed classes in the dict""" import cppyy cppyy.load_reflection_info(self.test_dct) assert cppyy.gbl.crossing == cppyy.gbl.crossing crossing = cppyy.gbl.crossing assert crossing.A == crossing.A
def test01_load_failure(self): """Test failure to load dictionary""" import cppyy raises(RuntimeError, cppyy.load_reflection_info, "does_not_exist.so") try: cppyy.load_reflection_info("does_not_exist.so") except RuntimeError as e: assert "does_not_exist.so" in str(e)
def test01_crossing_dict(self): """Test availability of all needed classes in the dict""" import cppyy cppyy.load_reflection_info(self.test_dct) assert cppyy.gbl.crossing == cppyy.gbl.crossing crossing = cppyy.gbl.crossing assert crossing.A == crossing.A
def test01_load_failure(self): """Test failure to load dictionary""" import cppyy raises(RuntimeError, cppyy.load_reflection_info, "does_not_exist.so") try: cppyy.load_reflection_info("does_not_exist.so") except RuntimeError as e: assert "does_not_exist.so" in str(e)
def __init__(self): try: cppyy.load_reflection_info( 'lib/lexer_routines.so') # FIXME: load from *.cpp cppyy.include('src/lexer_routines.h') #cppyy.cppdefs(open(target)) from cppyy.gbl import lexer_routines except OSError as err: # no such directory print( dedent(''' Test not being run in the root directory ''')) raise
def test03a_namespace_lookup_on_update(self): """Test whether namespaces can be shared across dictionaries.""" import cppyy gbl = cppyy.gbl lib2 = cppyy.load_reflection_info("advancedcpp2Dict.so") assert gbl.a_ns is gbl.a_ns assert gbl.a_ns.d_ns is gbl.a_ns.d_ns assert gbl.a_ns.g_class is gbl.a_ns.g_class assert gbl.a_ns.g_class.h_class is gbl.a_ns.g_class.h_class assert gbl.a_ns.d_ns.i_class is gbl.a_ns.d_ns.i_class assert gbl.a_ns.d_ns.i_class.j_class is gbl.a_ns.d_ns.i_class.j_class assert gbl.a_ns.g_g == 77 assert gbl.a_ns.get_g_g() == 77 assert gbl.a_ns.g_class.s_g == 88 assert gbl.a_ns.g_class().m_g == -7 assert gbl.a_ns.g_class.h_class.s_h == 99 assert gbl.a_ns.g_class.h_class().m_h == -8 assert gbl.a_ns.d_ns.g_i == 111 assert gbl.a_ns.d_ns.get_g_i() == 111 assert gbl.a_ns.d_ns.i_class.s_i == 222 assert gbl.a_ns.d_ns.i_class().m_i == -9 assert gbl.a_ns.d_ns.i_class.j_class.s_j == 333 assert gbl.a_ns.d_ns.i_class.j_class().m_j == -10
def __init__(self): import cppyy self.lib = cppyy.load_reflection_info("./example01Dict.so") self.cls = cppyy.gbl.example01 self.inst = self.cls(0)
def test03a_namespace_lookup_on_update(self): """Test whether namespaces can be shared across dictionaries.""" import cppyy gbl = cppyy.gbl lib2 = cppyy.load_reflection_info("advancedcpp2Dict.so") assert gbl.a_ns is gbl.a_ns assert gbl.a_ns.d_ns is gbl.a_ns.d_ns assert gbl.a_ns.g_class is gbl.a_ns.g_class assert gbl.a_ns.g_class.h_class is gbl.a_ns.g_class.h_class assert gbl.a_ns.d_ns.i_class is gbl.a_ns.d_ns.i_class assert gbl.a_ns.d_ns.i_class.j_class is gbl.a_ns.d_ns.i_class.j_class assert gbl.a_ns.g_g == 77 assert gbl.a_ns.get_g_g() == 77 assert gbl.a_ns.g_class.s_g == 88 assert gbl.a_ns.g_class().m_g == -7 assert gbl.a_ns.g_class.h_class.s_h == 99 assert gbl.a_ns.g_class.h_class().m_h == -8 assert gbl.a_ns.d_ns.g_i == 111 assert gbl.a_ns.d_ns.get_g_i() == 111 assert gbl.a_ns.d_ns.i_class.s_i == 222 assert gbl.a_ns.d_ns.i_class().m_i == -9 assert gbl.a_ns.d_ns.i_class.j_class.s_j == 333 assert gbl.a_ns.d_ns.i_class.j_class().m_j == -10
def setup_class(cls): cls.test_dct = test_dct import cppyy cls.datatypes = cppyy.load_reflection_info(cls.test_dct) cls.N = cppyy.gbl.N cls.has_byte = 201402 < cppyy.gbl.gInterpreter.ProcessLine( "__cplusplus;")
def __init__(self): import cppyy self.lib = cppyy.load_reflection_info("./example01Dict.so") self.cls = cppyy._scope_byname("example01") self.inst = self.cls.get_overload(self.cls.type_name).call(None, 0)
def setup_class(cls): # we need to import ROOT because in macOS if a cppyy env # variable is not set libcppyy_backend cannot be found import ROOT import cppyy cls.test_dct = "Pythonizables_C" cls.pythonizables = cppyy.load_reflection_info(cls.test_dct) cls.exp_pyroot = os.environ.get('EXP_PYROOT') == 'True'
def setup_class(cls): # we need to import ROOT because in macOS if a cppyy env # variable is not set libcppyy_backend cannot be found import ROOT import cppyy cls.test_dct = "SmartPtr_C" cls.smartptr = cppyy.load_reflection_info(cls.test_dct) # We need to introduce it in order to distinguish between # _get_smart_ptr in old Cppyy and __smartptr__ in new Cppyy cls.exp_pyroot = os.environ.get('EXP_PYROOT') == 'True'
def run(input_files, output_file): ## Bit of extra configuration from GaudiConf import IOHelper IOHelper().inputFiles(input_files) HistogramPersistencySvc().OutputFile = output_file.replace('.root', '_histos.root') ## GaudiPython import GaudiPython import cppyy cppyy.load_reflection_info('libLinkerEvent') cppyy.load_reflection_info('libLinkerInstancesDict') from GaudiPython.Bindings import AppMgr appMgr = AppMgr(outputlevel = 3) appMgr.config() appMgr.HistogramPersistency = 'ROOT' ntSvc = GaudiPython.iService('NTupleSvc') ntSvc.Output = ["MATCHZERRLUN DATAFILE='{0}' OPT='NEW'".format(output_file)] from Hlt1Muons.MatchAlgo import MatchResidualAlgo match_algo = MatchResidualAlgo("MatchResidualAlgo", MatchVeloMuon = mvm.getFullName()) match_algo.NTupleLUN = 'MATCHZERRLUN' appMgr.addAlgorithm(match_algo) from Hlt1Muons.MatchAlgo import MatchChi2Algo chi2_algo = MatchChi2Algo("MatchChi2Algo", MatchVeloMuon = mvm_chi2.getFullName()) chi2_algo.NTupleLUN = 'MATCHZERRLUN' appMgr.addAlgorithm(chi2_algo) if mvm_old: chi2_algo_old = MatchChi2Algo("MatchChi2AlgoOld", MatchVeloMuon = mvm_old.getFullName()) chi2_algo_old.NTupleLUN = 'MATCHZERRLUN' appMgr.addAlgorithm(chi2_algo_old) appMgr.initialize() appMgr.run(options.nevents) appMgr.stop() appMgr.finalize() appMgr.exit()
def setup_class(cls): import cppyy cls.test_dct = "DataTypes_C" cls.datatypes = cppyy.load_reflection_info(cls.test_dct) cls.N = cppyy.gbl.N cls.exp_pyroot = os.environ.get('EXP_PYROOT') == 'True' if cls.exp_pyroot: # In new Cppyy, nullptr can't be found in gbl. # Take it from libcppyy (we could also use ROOT.nullptr) import libcppyy cls.nullptr = libcppyy.nullptr else: cls.nullptr = cppyy.gbl.nullptr
def setup_class(cls): cls.test_dct = test_dct import cppyy cls.cpp11features = cppyy.load_reflection_info(cls.test_dct)
def setup_class(cls): import cppyy cls.test_dct = "Overloads_C" cls.datatypes = cppyy.load_reflection_info(cls.test_dct)
def setup_class(cls): cls.test_dct = test_dct import cppyy cls.cpp11features = cppyy.load_reflection_info(cls.test_dct)
def setup_class(cls): cls.test_dct = test_dct import cppyy cls.datatypes = cppyy.load_reflection_info(cls.test_dct)
'CAFAnaExtrap', 'CAFAnaPrediction', 'CAFAnaExperiment', 'CAFAnaAnalysis', 'SBNAnaVars', 'SBNAnaCuts']: print(' ', lib) ROOT.gSystem.Load('lib'+lib+'.so') import cppyy print('Load dictionaries... (please ignore errors about .pcm files)') for d in ['CAFAna', 'SBNAna']: print(' ', d) cppyy.load_reflection_info('lib'+d+'_dict.so') class PyCAFAna: def __init__(self, cppyy): self._cppyy = cppyy def CSliceVar(self, body): '''Construct a new slice Var given the C++ body as a string''' var = 'pyvar_'+self._cppyy.gbl.ana.UniqueName() text = '#include "StandardRecord/Proxy/SRProxy.h"\ndouble '+var+'_func(const caf::SRSliceProxy* srp){\nconst caf::SRSliceProxy& sr = *srp;\n'+body+'\n}\nconst ana::Var '+var+'('+var+'_func);' self._cppyy.cppdef(text) return getattr(self._cppyy.gbl, var) def CSpillVar(self, body): '''Construct a new spill Var given the C++ body as a string''' var = 'pyvar_'+self._cppyy.gbl.ana.UniqueName()
def setup_class(cls): cls.test_dct = test_dct import cppyy cls.fragile = cppyy.load_reflection_info(cls.test_dct)
def test01_load_reflection_cache(self): """Loading reflection info twice should result in the same object""" import cppyy lib2 = cppyy.load_reflection_info(self.test_dct) assert self.datatypes is lib2
def setup_class(cls): cls.test_dct = test_dct import cppyy cls.stltypes = cppyy.load_reflection_info(cls.test_dct) cls.N = cppyy.gbl.N
def setup_class(cls): cls.test_dct = test_dct import cppyy cls.fragile = cppyy.load_reflection_info(cls.test_dct)
def setup_class(cls): import cppyy cls.test_dct = "DataTypes_C" cls.datatypes = cppyy.load_reflection_info(cls.test_dct) cls.N = cppyy.gbl.N
def setup_class(cls): import cppyy cls.test_dct = "SmartPtr_C" cls.smartptr = cppyy.load_reflection_info(cls.test_dct)
def setup_class(cls): import cppyy cls.test_dct = "SmartPtr_C" cls.smartptr = cppyy.load_reflection_info(cls.test_dct)
#*-* - a one dimensional histogram #*-* - a two dimensional histogram #*-* - a profile histogram #*-* - a memory-resident ntuple #*-* #*-* These objects are filled with some random numbers and saved on a file. #*-* #*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* _reflex = True # to keep things equal, set to False for full macro try: import cppyy, random if not hasattr(cppyy.gbl, 'gROOT'): cppyy.load_reflection_info('bench02Dict_reflex.so') _reflex = True TCanvas = cppyy.gbl.TCanvas TFile = cppyy.gbl.TFile TProfile = cppyy.gbl.TProfile TNtuple = cppyy.gbl.TNtuple TH1F = cppyy.gbl.TH1F TH2F = cppyy.gbl.TH2F TRandom3 = cppyy.gbl.TRandom3 gROOT = cppyy.gbl.gROOT gBenchmark = cppyy.gbl.TBenchmark() gSystem = cppyy.gbl.gSystem except ImportError:
#*-* This program creates : #*-* - a one dimensional histogram #*-* - a two dimensional histogram #*-* - a profile histogram #*-* - a memory-resident ntuple #*-* #*-* These objects are filled with some random numbers and saved on a file. #*-* #*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* try: import warnings warnings.simplefilter("ignore") import cppyy, random cppyy.load_reflection_info('bench02Dict_reflex.so') app = cppyy.gbl.Bench02RootApp() TCanvas = cppyy.gbl.TCanvas TFile = cppyy.gbl.TFile TProfile = cppyy.gbl.TProfile TNtuple = cppyy.gbl.TNtuple TH1F = cppyy.gbl.TH1F TH2F = cppyy.gbl.TH2F TRandom = cppyy.gbl.TRandom except ImportError: from ROOT import TCanvas, TFile, TProfile, TNtuple, TH1F, TH2F, TRandom import random import math
def setup_class(cls): cls.test_dct = test_dct import cppyy cls.example01 = cppyy.load_reflection_info(cls.test_dct)
def test01_load_reflection_cache(self): """Loading reflection info twice should result in the same object""" import cppyy lib2 = cppyy.load_reflection_info(self.test_dct) assert self.datatypes is lib2
def test01_load_dictionary_cache(self): """Test whether loading a dictionary twice results in the same object.""" import cppyy lib2 = cppyy.load_reflection_info(self.test_dct) assert self.example01 is lib2
def initialize(pkg, lib_file, map_file, noisy=False): """ Initialise the bindings module. :param pkg: The bindings package. :param __init__py: Base __init__.py file of the bindings. :param cmake_shared_library_prefix: ${cmake_shared_library_prefix} :param cmake_shared_library_suffix: ${cmake_shared_library_suffix} """ def add_to_pkg(file, keyword, simplenames, children): def map_operator_name(name): """ Map the given C++ operator name on the python equivalent. """ CPPYY__idiv__ = "__idiv__" CPPYY__div__ = "__div__" gC2POperatorMapping = { "[]": "__getitem__", "()": "__call__", "/": CPPYY__div__, "%": "__mod__", "**": "__pow__", "<<": "__lshift__", ">>": "__rshift__", "&": "__and__", "|": "__or__", "^": "__xor__", "~": "__inv__", "+=": "__iadd__", "-=": "__isub__", "*=": "__imul__", "/=": CPPYY__idiv__, "%=": "__imod__", "**=": "__ipow__", "<<=": "__ilshift__", ">>=": "__irshift__", "&=": "__iand__", "|=": "__ior__", "^=": "__ixor__", "==": "__eq__", "!=": "__ne__", ">": "__gt__", "<": "__lt__", ">=": "__ge__", "<=": "__le__", } op = name[8:] result = gC2POperatorMapping.get(op, None) if result: return result bTakesParams = 1 if op == "*": # dereference v.s. multiplication of two instances return "__mul__" if bTakesParams else "__deref__" elif op == "+": # unary positive v.s. addition of two instances return "__add__" if bTakesParams else "__pos__" elif op == "-": # unary negative v.s. subtraction of two instances return "__sub__" if bTakesParams else "__neg__" elif op == "++": # prefix v.s. postfix increment return "__postinc__" if bTakesParams else "__preinc__" elif op == "--": # prefix v.s. postfix decrement return "__postdec__" if bTakesParams else "__predec__" # might get here, as not all operator methods are handled (new, delete, etc.) return name # # Add level 1 objects to the pkg namespace. # if len(simplenames) > 1: return # # Ignore some names based on heuristics. # simplename = simplenames[0] if simplename in ('void', 'sizeof', 'const'): return if simplename[0] in '0123456789': # # Don't attempt to look up numbers (i.e. non-type template parameters). # return if PRIMITIVE_TYPES.search(simplename): return if simplename.startswith("operator"): simplename = map_operator_name(simplename) # # Classes, variables etc. # try: entity = getattr(cppyy.gbl, simplename) except AttributeError as e: if noisy: print("Unable to lookup {}:{} cppyy.gbl.{} ({})".format(file, keyword, simplename, children)) else: if getattr(entity, "__module__", None) == "cppyy.gbl": setattr(entity, "__module__", pkg) setattr(pkg_module, simplename, entity) pkg_dir = os.path.dirname(__file__) if "." in pkg: pkg_namespace, pkg_simplename = pkg.rsplit(".", 1) else: pkg_namespace, pkg_simplename = "", pkg pkg_module = sys.modules[pkg] # # Load the library. # cppyy.load_reflection_info(os.path.join(pkg_dir, lib_file)) # # Load pythonizations # Has to be done before the mapping, otherwise the names from our library # that are in the global namespace will be compiled when injected, before # having their pythonizors applied # pythonization_files = glob.glob(os.path.join(pkg_dir, '**/pythonize*.py'), recursive=True) add_pythonizations(pythonization_files, noisy=noisy) # # Parse the map file. # with open(os.path.join(pkg_dir, map_file), 'r') as map_file: files = json.load(map_file) # # Iterate over all the items at the top level of each file, and add them # to the pkg. # for file in files: for child in file["children"]: if not child["kind"] in ('class', 'var', 'namespace', 'typedef'): continue simplenames = child["name"].split('::') add_to_pkg(file["name"], child["kind"], simplenames, child)
def setup_class(cls): cls.test_dct = test_dct import cppyy cls.stltypes = cppyy.load_reflection_info(cls.test_dct)
def setup_class(cls): import cppyy cls.test_dct = "Pythonizables_C" cls.pythonizables = cppyy.load_reflection_info(cls.test_dct)
def test01_load_reflection_cache(self): """Test whether loading a refl. info twice results in the same object.""" import cppyy lib2 = cppyy.load_reflection_info(self.test_dct) assert self.datatypes is lib2
import py, pytest, os, sys, math, warnings from support import setup_make setup_make("runvectorDict.so") currpath = py.path.local(__file__).dirpath() test_dct = str(currpath.join("runvectorDict.so")) import cppyy cppyy.load_reflection_info(test_dct) all_configs = [('cppyy', 'cppyy.gbl')] preamble = "@pytest.mark.benchmark(group=group, warmup=True)" try: import __pypy__ import py_runvector all_configs.append(('py', 'py_runvector')) # too slow to run on CPython except ImportError: try: import py11_runvector all_configs.append(('py11', 'py11_runvector')) py11 = True except ImportError: warnings.warn('pybind11 tests disabled') py11 = False try: import swig_runvector all_configs.append(('swig', 'swig_runvector.cvar'))
def setup_class(cls): import cppyy cls.test_dct = "StlTypes_C" cls.datatypes = cppyy.load_reflection_info(cls.test_dct)
def test01_load_reflection_cache(self): """Test whether loading a refl. info twice results in the same object.""" import cppyy lib2 = cppyy.load_reflection_info(self.test_dct) assert self.datatypes is lib2
def setup_class(cls): cls.test_dct = test_dct import cppyy cls.advanced = cppyy.load_reflection_info(cls.test_dct)
def setup_class(cls): cls.test_dct = test_dct import cppyy cls.datatypes = cppyy.load_reflection_info(cls.test_dct) cls.N = cppyy.gbl.N
def setup_class(cls): cls.test_dct = test_dct import cppyy cls.example01 = cppyy.load_reflection_info(cls.test_dct)
import ROOT import cppyy import os if "CMSSW_BASE" not in os.environ: # This is a standalone compile file_path = os.path.abspath(__file__) base_path = os.path.dirname(os.path.dirname(os.path.dirname(file_path))) cppyy.load_library(base_path + "/lib/libPlotUtils.so") cppyy.load_reflection_info(base_path + "/python/libpyPlotUtils.so") ## Renaming all the stuff to use a flatter interface # Unfortunately, the contents of cppyy userspace is dynamically generated, so # there is not easy way for programmatically running this renaming scheme. Simple1DCanvas = cppyy.gbl.usr.plt.Simple1DCanvas Ratio1DCanvas = cppyy.gbl.usr.plt.Ratio1DCanvas Flat2DCanvas = cppyy.gbl.usr.plt.Flat2DCanvas CommonXCanvas = cppyy.gbl.usr.plt.CommonXCanvas Pad1D = cppyy.gbl.usr.plt.Pad1D Pad2DFlat = cppyy.gbl.usr.plt.Pad2DFlat PlotUnder = cppyy.gbl.usr.plt.PlotUnder ExtryText = cppyy.gbl.usr.plt.EntryText TextColor = cppyy.gbl.usr.plt.TextColor TextSize = cppyy.gbl.usr.plt.TextSize TextAngle = cppyy.gbl.usr.plt.TextAngle TextAlign = cppyy.gbl.usr.plt.TextAlign LineColor = cppyy.gbl.usr.plt.LineColor LineStyle = cppyy.gbl.usr.plt.LineStyle LineWidth = cppyy.gbl.usr.plt.LineWidth FillColor = cppyy.gbl.usr.plt.FillColor
def setup_class(cls): cls.test_dct = test_dct import cppyy cls.advanced = cppyy.load_reflection_info(cls.test_dct)
def test01_load_dictionary_cache(self): """Test whether loading a dictionary twice results in the same object""" import cppyy lib2 = cppyy.load_reflection_info(self.test_dct) assert self.example01 is lib2
def setup_class(cls): cls.test_dct = test_dct import cppyy # touch __version__ as a test assert hasattr(cppyy, '__version__') cls.doc_helper = cppyy.load_reflection_info(cls.test_dct) cppyy.cppdef(""" #include <cmath> #include <iostream> #include <vector> //----- unsigned int gUint = 0; //----- class Abstract { public: virtual ~Abstract() {} virtual std::string abstract_method() = 0; virtual void concrete_method() = 0; }; void Abstract::concrete_method() { std::cout << "called Abstract::concrete_method" << std::endl; } //----- class Concrete : Abstract { public: Concrete(int n=42) : m_int(n), m_const_int(17) {} ~Concrete() {} virtual std::string abstract_method() { return "called Concrete::abstract_method"; } virtual void concrete_method() { std::cout << "called Concrete::concrete_method" << std::endl; } void array_method(int* ad, int size) { for (int i=0; i < size; ++i) std::cerr << ad[i] << ' '; std::cerr << '\\n'; // TODO: not std::endl for 32b Windows } void array_method(double* ad, int size) { for (int i=0; i < size; ++i) std::cerr << ad[i] << ' '; std::cerr << '\\n'; // TODO: not std::endl for 32b Windows } void uint_ref_assign(unsigned int& target, unsigned int value) { target = value; } Abstract* show_autocast() { return this; } operator const char*() { return "Hello operator const char*!"; } public: double m_data[4]; int m_int; const int m_const_int; static int s_int; }; typedef Concrete Concrete_t; int Concrete::s_int = 321; std::string call_abstract_method(Abstract* a) { return a->abstract_method(); } //----- int global_function(int) { return 42; } double global_function(double) { return std::exp(1); } int call_int_int(int (*f)(int, int), int i1, int i2) { return f(i1, i2); } template<class A, class B, class C = A> C multiply(A a, B b) { return C{a*b}; } //----- namespace Namespace { class Concrete { public: class NestedClass { public: std::vector<int> m_v; }; }; int global_function(int i) { return 2*::global_function(i); } double global_function(double d) { return 2*::global_function(d); } //----- enum EFruit {kApple=78, kBanana=29, kCitrus=34}; enum class NamedClassEnum { E1 = 42 }; } // namespace Namespace """)
def setup_class(cls): import cppyy cls.test_dct = "Pythonizables_C" cls.pythonizables = cppyy.load_reflection_info(cls.test_dct)
def __init__(self): import cppyy self.lib = cppyy.load_reflection_info("./example01Dict.so") self.cls = cppyy.gbl.example01 self.inst = self.cls(0)
def __init__(self): import cppyy self.lib = cppyy.load_reflection_info("./example01Dict.so") self.cls = cppyy._scope_byname("example01") self.inst = self.cls.get_overload(self.cls.type_name).call(None, 0)
def setup_class(cls): cls.test_dct = test_dct import cppyy cls.streams = cppyy.load_reflection_info(cls.test_dct)
import py, pytest, os, sys, math, warnings from support import setup_make setup_make("runvectorDict.so") currpath = py.path.local(__file__).dirpath() test_dct = str(currpath.join("runvectorDict.so")) import cppyy cppyy.load_reflection_info(test_dct) all_configs = [('cppyy', 'cppyy.gbl')] preamble = "@pytest.mark.benchmark(group=group, warmup=True)" try: import __pypy__ import py_runvector all_configs.append(('py', 'py_runvector')) # too slow to run on CPython except ImportError: try: import py11_runvector all_configs.append(('py11', 'py11_runvector')) py11 = True except ImportError: warnings.warn('pybind11 tests disabled') py11 = False try:
def initialise(pkg, __init__py, cmake_shared_library_prefix, cmake_shared_library_suffix): """ Initialise the bindings module. :param pkg: The bindings package. :param __init__py: Base __init__.py file of the bindings. :param cmake_shared_library_prefix: ${cmake_shared_library_prefix} :param cmake_shared_library_suffix: ${cmake_shared_library_suffix} """ def add_to_pkg(file, keyword, simplenames, children): def map_operator_name(name): """ Map the given C++ operator name on the python equivalent. """ CPPYY__idiv__ = "__idiv__" CPPYY__div__ = "__div__" gC2POperatorMapping = { "[]": "__getitem__", "()": "__call__", "/": CPPYY__div__, "%": "__mod__", "**": "__pow__", "<<": "__lshift__", ">>": "__rshift__", "&": "__and__", "|": "__or__", "^": "__xor__", "~": "__inv__", "+=": "__iadd__", "-=": "__isub__", "*=": "__imul__", "/=": CPPYY__idiv__, "%=": "__imod__", "**=": "__ipow__", "<<=": "__ilshift__", ">>=": "__irshift__", "&=": "__iand__", "|=": "__ior__", "^=": "__ixor__", "==": "__eq__", "!=": "__ne__", ">": "__gt__", "<": "__lt__", ">=": "__ge__", "<=": "__le__", } op = name[8:] result = gC2POperatorMapping.get(op, None) if result: return result print(children) bTakesParams = 1 if op == "*": # dereference v.s. multiplication of two instances return "__mul__" if bTakesParams else "__deref__" elif op == "+": # unary positive v.s. addition of two instances return "__add__" if bTakesParams else "__pos__" elif op == "-": # unary negative v.s. subtraction of two instances return "__sub__" if bTakesParams else "__neg__" elif op == "++": # prefix v.s. postfix increment return "__postinc__" if bTakesParams else "__preinc__" elif op == "--": # prefix v.s. postfix decrement return "__postdec__" if bTakesParams else "__predec__" # might get here, as not all operator methods are handled (new, delete, etc.) return name # # Add level 1 objects to the pkg namespace. # if len(simplenames) > 1: return # # Ignore some names based on heuristics. # simplename = simplenames[0] if simplename in ('void', 'sizeof', 'const'): return if simplename[0] in '0123456789': # # Don't attempt to look up numbers (i.e. non-type template parameters). # return if PRIMITIVE_TYPES.search(simplename): return if simplename.startswith("operator"): simplename = map_operator_name(simplename) # # Classes, variables etc. # try: entity = getattr(cppyy.gbl, simplename) except AttributeError as e: print(_("Unable to lookup {}:{} cppyy.gbl.{} ({})").format(file, keyword, simplename, children)) #raise else: if getattr(entity, "__module__", None) == "cppyy.gbl": setattr(entity, "__module__", pkg) setattr(pkg_module, simplename, entity) pkg_dir = os.path.dirname(__init__py) if "." in pkg: pkg_namespace, pkg_simplename = pkg.rsplit(".", 1) else: pkg_namespace, pkg_simplename = "", pkg pkg_module = sys.modules[pkg] lib_name = pkg_namespace + pkg_simplename + "Cppyy" lib_file = cmake_shared_library_prefix + lib_name + cmake_shared_library_suffix map_file = os.path.join(pkg_dir, pkg_simplename + ".map") # # Load the library. # cppyy.load_reflection_info(os.path.join(pkg_dir, lib_file)) # # Parse the map file. # with open(map_file, 'rU') as map_file: files = json.load(map_file) # # Iterate over all the items at the top level of each file, and add them # to the pkg. # for file in files: for child in file["children"]: if not child["kind"] in ('class', 'var', 'namespace', 'typedef'): continue simplenames = child["name"].split('::') add_to_pkg(file["name"], child["kind"], simplenames, child) # # Load any customisations. # extra_pythons = glob.glob(os.path.join(pkg_dir, "extra_*.py")) for extra_python in extra_pythons: extra_module = os.path.basename(extra_python) extra_module = pkg + "." + os.path.splitext(extra_module)[0] # # Deleting the modules after use runs the risk of GC running on # stuff we are using, such as ctypes.c_int. # extra = load_source(extra_module, extra_python) # # Valid customisations are routines named "c13n_<something>". # fns = inspect.getmembers(extra, predicate=inspect.isroutine) fns = {fn[0]: fn[1] for fn in fns if fn[0].startswith("c13n_")} for fn in sorted(fns): fns[fn](pkg_module)