python - 返回 Cython 数组

标签 python c++ cython cpython

如何正确初始化并返回一个 Cython 数组?例如:

cdef public double* cyTest(double[] input):
  cdef double output[3]

  for i in xrange(3):
    output[i] = input[i]**2
    print 'loop: ' + str(output[i])
  return output

cdef double* test = [1,2,3]
cdef double* results = cyTest(test)

for i in xrange(3):
  print 'return: ' + str(results[i])

返回:

loop: 1.0->1.0
loop: 2.0->4.0
loop: 3.0->9.0
return: 1.88706086937e-299
return: 9.7051011575e+236
return: 1.88706086795e-299

很明显,results 仍然只指向垃圾,而不是它应该指向的值。诚然,我对混合使用指针和数组语法以及在 Cython 上下文中哪个更可取/可能感到有点困惑。

最后,我想从纯 C++ 函数调用 cyTest:

#include <iostream>
#include <Python.h>
#include "cyTest.h"

void main() {
  Py_Initialize();
  initcyTest();
  double input[3] = {1,2,3};
  double* output = cyTest(input);

  for(int i = 0; i < 3; i++)
    std::cout << "cout: " << output[i] << std::endl;

  Py_Finalize();
}

这会返回类似的结果:

loop: 1.0->1.0
loop: 2.0->4.0
loop: 3.0->9.0
cout: 1
cout: 6.30058e+077
cout: 6.39301e-308

有人愿意解释我犯了什么错误吗?我想让它尽可能简单。毕竟它只是将一个数组从 Cython 返回到 C++。如果不需要,我稍后会处理动态内存分配。

最佳答案

您正在返回对本地数组 ( output ) 的引用,这将不起作用。

尝试将脚本更改为:

from cpython.mem cimport PyMem_Malloc

cdef public double * cyTest(double[] input):
    cdef double * output = < double * >PyMem_Malloc( sizeof(double) * 3 )
    for i in xrange(3):
        output[i] = input[i]**2
        print 'loop: ' + str(output[i])
    return output

在你的 C++ 代码中,

在你使用完double* output 问题之后 free( output );

如果你想在你的 pyx 脚本中使用 cdef double* results = cyTest(test) 然后不要忘记使用 PyMem_Free(results)

关于python - 返回 Cython 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25205140/

相关文章:

python - 链接外部 C 库时来自 Cython 的 ImportError

python - 从嘈杂的车牌上分割每个字符

python - 更新当前显示的变量

python - 如何从多个项目的缓冲区中生成单个项目并定期重新填充缓冲区?

c++ - leetcode : can someone explain why this method works? 中的最大数

c++ - 返回指针的开头?

与网站调用相比,Python 请求给出不同的状态代码

c++ - 如何使用 visual studio 2015 正确调试 MFC 容器

python - python 错误的 cython 包装器中的 AttributeError

python - 在 IPython 中运行 %%cython-magic 单元时出现 CompileError/LinkerError : "command ' gcc' failed with exit status 1"mean, 是什么意思