Call python script from c++ without loading the file each time -
i have python script need call lots of times (around 160000 times) , while can in less second hard c++ code, if try load , call python script this, take hours! think if loaded script once, run loaded script on , over, faster. unfortunately, don't know how this. don't think can load file ifstream, use pyrun_simplestring on lines of string. in case isn't faster however, possible return 2d array in python, convert array std::vector?
consider following function, in file called multiply.py
#!/usr/bin/python3 def do_multiply(a, b): c = 0 in range(0, a): c += b return c in c++ file:
// load function pyobject *pname = pyunicode_fromstring("multiply"); pyobject *pmodule = pyimport_import(pname); pyobject *pfunction = pyobject_getattrstring(pmodule, "do_multiply") let's want call function 3 times, follows:
struct numberpair { int x; int y; }; std::vector<numberpair> numberpairs { {1, 2}, {5, 6}, {10, 12} }; then, can call pyobject_callfunction several times, while module loaded:
for(const auto &numberpair : numberpairs) { pyobject *product = pyobject_callfunction(pfunction, "ii", numberpair.x, numberpair.y); if(product != null) { std::cout << "product " << pylong_aslong(product) << '\n'; py_decref(product); } } there no need close module between calls pyobject_callfunction, shouldn't problem.
Comments
Post a Comment