c++ - 将 python 与 C++ 集成
问题描述
我想将python
代码与集成C++
,其中c++
源代码在python
. 我特别需要将数组从c++
代码传递到代码并从源代码中python
获取另一个数组。举例来说,python
c++
main.cc
// call_function.c - A sample of calling
// python functions from C code
//
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <Python.h>
#include <iostream>
#include "numpy/arrayobject.h"
int main(int argc, char *argv[])
{
PyObject *pName, *pModule, *pDict, *pFunc, *pValue, *pRet;
const int SIZE{ 10 };
npy_intp dims = SIZE;
const int ND{ 1 };
double* a = new double[10]();
double* b = new double[10]();
if (a == NULL)
{
exit(1);
}
std::cout << a[1] << std::endl;
// Initialize the Python Interpreter
Py_Initialize();
import_array();
PyRun_SimpleString("import sys\n");
PyRun_SimpleString("sys.path.append(\"/home/mehdi\")");
// Build the name object
pName = PyUnicode_FromString("pytst");
if (pName == NULL) exit(1);
// Load the module object
pModule = PyImport_Import(pName);
if (pModule == NULL) exit(1);
Py_DECREF(pName);
if (!pModule){
std::cout << "mymodule can not be imported" << std::endl;
return 1;
}
// pDict is a borrowed reference
pDict = PyModule_GetDict(pModule);
if (pDict == NULL) exit(1);
PyObject *pArraya = PyArray_SimpleNewFromData(ND, &dims, NPY_DOUBLE,
reinterpret_cast<void*>(a));
import_array();
PyArrayObject *np_arra = reinterpret_cast<PyArrayObject*>(pArraya);
PyObject *pArrayb = PyArray_SimpleNewFromData(
ND, &dims, NPY_LONGDOUBLE, reinterpret_cast<void*>(b));
PyArrayObject *np_arrb = reinterpret_cast<PyArrayObject*>(pArrayb);
if (!pArraya || !pArrayb)
std::cout << "Error" << std::endl;
// pFunc is also a borrowed reference
pFunc = PyDict_GetItemString(pDict, "multiply");
if (PyCallable_Check(pFunc))
{
pRet = PyObject_CallObject(pFunc, pArraya);
} else
{
PyErr_Print();
}
if (!pRet)
std::cout << "error" << std::endl;
if (!PyArray_Check(pRet)) {
std::cerr << " did not return an array." << std::endl;
}
if (pRet == NULL) exit(1);
std::cout << 9 << std::endl;
PyArrayObject *np_ret = reinterpret_cast<PyArrayObject*>(pRet);
double* c_out;
//int len = PyArray_SHAPE(np_ret)[0];
std::cout << 10 << std::endl;
c_out = reinterpret_cast<double*>(PyArray_DATA(np_ret));
// Clean up
Py_DECREF(pModule);
Py_DECREF(pName);
// Finish the Python Interpreter
Py_Finalize();
return 0;
}
}
pytst.py
import numpy as np
def multiply(a, b):
c = np.array([])
for i in range(10):
c = np.append(c, a[i] + b[i])
return c
并编译它我使用
g++ -Wall main.cc -o main -I/usr/include/python3.8 -I /usr/local/lib/python3.5/dist-packages/numpy/core/include
.
我转换double*
为从到PyObject*
传递。但我得到了(从python代码返回数组到c++)。如果有人让我知道代码和代码之间的这种通信是如何发生的,我将不胜感激。python
c++
NULL
pRet
c++
python
解决方案
Python 使用基于 PyObject 的变体类型来做所有事情;您将需要创建代表包含双打列表的 PyObject 实例,例如
PyObject* alist = PyList_New(10);
for (i= 0; i < 10; i++)
{
PyList_SetItem(alist, 0, PyFloat_FromDouble(a[i]));
}
...etc...
[编辑] 当您调用 Python 方法时,您需要将参数作为元组传递,例如:
PyObject* parameters = PyTuple_New(2);
PyTuple_SetItem(parameters, 0, pArraya);
PyTuple_SetItem(parameters, 1, pArrayb);
pRet = PyObject_CallObject(pFunc, parameters);
Py_DECREF(parameters);
另请查看一些在线示例,例如 https://gist.github.com/nad2000/9f69c5096e10c34acddb
我推荐使用 Cython,它比 CPython 好用得多,而且网上有很多教程。
推荐阅读
- c - 如何在C中清空字符串的静态数组
- java - 如何获得对处理当前请求的端点方法的引用(不是当前方法)
- python - sqlalchemy:'metadata.drop_all' 不起作用
- swift - 更新 Firebase ChildByAutoID
- azure - 将 JSON 文件导入 Azure 数据库
- json - 在 laravel Blade 中获取 Json 信息
- python - Apache Beam - Python - 读取文件
- java - Spring AOP - 提取方法和参数注释
- reactjs - Heroku 无法解析模块 react-dom”
- javascript - ajax上传文件formdata看起来是空的