我有很多C函数,我想从python中调用它们.cython似乎是要走的路,但我无法真正找到一个如何做到这一点的例子.我的C函数看起来像这样:
void calculate_daily ( char *db_name, int grid_id, int year,
double *dtmp, double *dtmn, double *dtmx,
double *dprec, double *ddtr, double *dayl,
double *dpet, double *dpar ) ;
Run Code Online (Sandbox Code Playgroud)
我想要做的就是指定前三个参数(一个字符串和两个整数),并恢复8个numpy数组(或python列表.所有双数组都有N个元素).我的代码假设指针指向已经分配的内存块.此外,生成的C代码应该链接到一些外部库.
我将发送一个c++
数组到python函数,numpy array
然后再返回另一个numpy array
.在查阅了numpy
文档和其他一些线程并调整代码后,最后代码正在运行,但我想知道这段代码是否以最佳方式编写,考虑到:
c++
和之间不必要地复制数组numpy (python)
.C++代码:
// python_embed.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include "Python.h"
#include "numpy/arrayobject.h"
#include<iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
Py_SetProgramName(argv[0]);
Py_Initialize();
import_array()
// Build the 2D array
PyObject *pArgs, *pReturn, *pModule, *pFunc;
PyArrayObject *np_ret, *np_arg;
const int SIZE{ 10 };
npy_intp dims[2]{SIZE, SIZE};
const int ND{ 2 }; …
Run Code Online (Sandbox Code Playgroud)