I'm trying to embed a python program to c++ code. the problem I have is to use python script that contain an numpy import. for example, if i use the following c++ code
#include <Python.h>
int main(int argc,char *argv[])
{
double
x=2.,
xp=4.,
dt=6.,
y=8,
yp=1,
dz=6;
Py_Initialize();
PyObject* myModuleString = PyString_FromString((char*)"log");
PyObject* myModule = PyImport_Import(myModuleString);
PyObject* myFunction = PyObject_GetAttrString(myModule,(char*)"derive");
PyObject* args = PyTuple_Pack( 6,
PyFloat_FromDouble(x),
PyFloat_FromDouble(xp),
PyFloat_FromDouble(dt),
PyFloat_FromDouble(y),
PyFloat_FromDouble(yp),
PyFloat_FromDouble(dz));
PyObject* myResult = PyObject_CallObject(myFunction, args);
PyObject *ts= PyTuple_GetItem(myResult,0);
PyObject *zs= PyTuple_GetItem(myResult,1);
double result_t = PyFloat_AsDouble(ts);
double result_z = PyFloat_AsDouble(zs);
printf("%3f \n %f \n", result_t,result_z);
Py_Finalize();
system("pause");
return 0;
}
with the following log.py script which contain the function derive
def derive(x,xp,dt,y,yp,dz):
return log(abs(x - xp)/dt),exp((y-yp)/dz)
it runs correctly, but if the log.py contain from numpy import array
, it fails
from numpy import array
def derive(x,xp,dt,y,yp,dz):
return log(abs(x - xp)/dt),exp((y-yp)/dz)
The Python "ModuleNotFoundError: No module named 'numpy'" occurs when we forget to install the numpy module before importing it or install it in an incorrect environment. To solve the error, install the module by running the pip install numpy command.
NumPy is usually imported under the np alias. alias: In Python alias are an alternate name for referring to the same thing. Now the NumPy package can be referred to as np instead of numpy .
import numpy as np a = np. array(...) from bitarray import bitarray as pp b = pp(...) import bitarray as pp b = pp. bitarray(...)
Why use NumPy? NumPy arrays are faster and more compact than Python lists. An array consumes less memory and is convenient to use. NumPy uses much less memory to store data and it provides a mechanism of specifying the data types.
I think you're linking statically but not retaining all of the symbols, which is required to load dynamic extension modules (i.e. -Xlinker -export-dynamic
). See Linking Requirements, which recommends that you query the correct options from distutils.sysconfig.get_config_var('LINKFORSHARED')
.
BTW, the variadic function Py_BuildValue
is a more convenient way to create args
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With