gpt4 book ai didi

c++ - 将 python 与 C++ 集成

转载 作者:行者123 更新时间:2023-12-01 14:47:00 27 4
gpt4 key购买 nike

我要整合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*转自 pythonc++ .但我得到 NULLpRet (将数组从 python 代码返回到 C++)。如果有人让我知道 c++ 之间的通信方式,我将不胜感激和 python代码发生。

最佳答案

Python 使用基于 PyObject 的变体类型来完成所有工作;您将需要创建表示包含 double 的列表的 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++ - 将 python 与 C++ 集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63572850/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com