Embedded python code in c++ - error when importing python libraries -
i trying use python 3.5 interpreter embedded in c++ program receive image c++, , use input trained tensorflow model. first, convert image numpy array , send python. simplified code works fine (codes adopted here):
python code:
def multiply_fun(m): v = m*2 print(v)
my c++ code calls function above:
#include <python.h> #include <abstract.h> #define npy_no_deprecated_api npy_1_7_api_version #include <ndarrayobject.h> #include <vector> int main() { py_initializeex(1); pyobject* syspath = pysys_getobject((char*)"path"); pyobject* curdir = pyunicode_fromstring("."); pylist_append(syspath, curdir); py_decref(curdir); pyobject* python_code = pyimport_importmodule("python_code"); pyobject* multiply_fun = pyobject_getattrstring(python_code, "multiply_fun"); py_xdecref(python_code); import_array1(-1); npy_intp dim[] = { 5, 5 }; std::vector<double> buffer(5*5, 1); pyobject* array_2d = pyarray_simplenewfromdata(2, dim, npy_double, &buffer[0]); pyobject* return_value1 = pyobject_callfunction(multiply_fun, "o", array_2d); py_xdecref(return_value1); py_xdecref(array_2d); py_xdecref(multiply_fun); py_finalize(); return 0; }
however, when want use of python libraries, got error. example, python code:
def multiply_fun(m): skimage.io import imsave imsave('test.png', m)
i got error:
exception ignored in: <module 'threading' 'c:\\users\\matin\\anaconda3\\lib\\threading.py'> traceback (most recent call last): file "c:\users\matin\anaconda3\lib\threading.py", line 1283, in _shutdown assert tlock.locked() systemerror: <built-in method locked of _thread.lock object @ 0x0000000002af4418> returned result error set
by way, this related discussion couldn't me.
thanks help.
edit 1: moving from skimage.io import imsave
outside of python function (as @moooeeeep suggested in comments) got null in line:
pyobject* python_code = pyimport_importmodule("python_code");
it seems problem pyimport_importmodule
cannot load submodules of packages when using from package.submodule import function
. has been explained in python/c api reference manual:
when name argument contains dot (when specifies submodule of package), fromlist argument set list ['*'] return value named module rather top-level package containing otherwise case. (unfortunately, has additional side effect when name in fact specifies subpackage instead of submodule: submodules specified in package’s all variable loaded.) return new reference imported module, or null exception set on failure. failing import of module doesn’t leave module in sys.modules.
this function uses absolute imports.
Comments
Post a Comment