Hi' i follow this tutorial to call the python function from a c++ code.
This is embeddedPython.cpp
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <iostream>
int
main(int argc, char *argv[])
{
PyObject *pName, *pModule, *pFunc;
PyObject *pArgs, *pValue;
int i;
if (argc < 3) {
fprintf(stderr,"Usage: call pythonfile funcname [args]\n");
return 1;
}
Py_Initialize();
pName = PyUnicode_DecodeFSDefault(argv[1]);
/* Error checking of pName left out */
std::cout << pName << std::endl;
pModule = PyImport_Import(pName);
Py_DECREF(pName);
if (pModule != NULL) {
pFunc = PyObject_GetAttrString(pModule, argv[2]);
/* pFunc is a new reference */
// didn't add the all code
}
return 0;
}
And test.py
def multiply(a,b):
print("Will compute", a, "times", b)
c = 0
for i in range(0, a):
c = c + b
return c
And finally CMakeLists.txt
cmake_minimum_required(VERSION 2.6)
project(demo)
find_package(PythonLibs REQUIRED)
include_directories(${PYTHON_INCLUDE_DIRS})
add_executable(demo embeddedPython.cpp)
target_link_libraries(demo ${PYTHON_LIBRARIES})
when I try to run the following command:
./demo test multiply 3 2
I get the following error.
AttributeError: module 'test' has no attribute 'multiply'
Cannot find function "multiply"
What could be the problem? I think; I can access the file but the code can't find the function.
The name of your Python file is test.py
but there is already a Python module test
for regression tests (see Python documentation) which doesn't contain a multiply() function. Rename your python file to avoid collision with existing modules. The example in the tutorial uses multiply.py
which works. I used test1.py
which works too.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments