I'm learning C++, and in particular C interface to Python. Right now, my focus is on calling or importing python objects from C++ main program.
I've been studying the following link but couldn't understand some concepts. ( https://www.codeproject.com/Articles/820116/Embedding-Python-program-in-aC-Cplusplus-code ) Following is the sections of the tutorial that I can't understand fully.
My questions are:
i. Is it correct for me to assume "CPyObject pFunc = PyObject_GetAttrString(pModule, "getInteger")" is doing this job?
ii.If I want to import a dataframe from python to C++ as a CPyObject, how can I manipulate this object in C++. I'm asking because there is no equivalent object to dataframe in C++. 3) Is there anything else I need to do to make sure my Python module file is visible and callable to C++? Such as saving them in the same folder?
Consider the following Python program, stored in pyemb3.py:
def getInteger():
print('Python function getInteger() called')
c = 100*50/30
return c
Now we want to call the function getInteger() from the following C++ code and print the value returned this function. This is the client C++ code:
#include <stdio.h>
#include <Python.h>
#include <pyhelper.hpp>
int main()
{
CPyInstance hInstance;
CPyObject pName = PyUnicode_FromString("pyemb3");
CPyObject pModule = PyImport_Import(pName);
if(pModule)
{
CPyObject pFunc = PyObject_GetAttrString(pModule, "getInteger");
if(pFunc && PyCallable_Check(pFunc))
{
CPyObject pValue = PyObject_CallObject(pFunc, NULL);
printf_s("C: getInteger() = %ld\n", PyLong_AsLong(pValue));
}
else
{
printf("ERROR: function getInteger()\n");
}
}
else
{
printf_s("ERROR: Module not imported\n");
}
return 0;
}
The problem is that 100*50/30
is not an integer , it is a float .
to get an integer use integer division: 100*50//30
If you are not sure about the returned type, you can use the Py_TYPE
macro on pValue
or just simply check for the type you are looking for with: PyLong_Check
or PyLong_CheckExact
1: if PyImport_Import
does not return null then the import was successful and the module was already executed by the time the function returned.
2: The PyObject_GetAttrString
or the PyObject_GetAttr
is the right way to get the imported module's objects.
3: Use these flags to ensure Python is embedded. Use Py_SetPath
before Py_Initialize
to add your module's path to sys.path
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.