简体   繁体   English

用C ++分配内存然后在Cython中解除分配?

[英]Allocate memory in C++ then deallocate it in Cython?

I have a C++ function that allocates an array and returns it. 我有一个C ++函数,它分配一个数组并返回它。 I want to use this array within Cython and then delete it when finished, but Cython doesn't seem to be happy with the way I'm trying to do this. 我想在Cython中使用这个数组,然后在完成后删除它,但Cython似乎对我尝试这样做的方式不满意。 The most trivial example: 最简单的例子:

foo.hpp: foo.hpp:

float * my_fun() { return new float[5]; }

foo.pyx: foo.pyx:

cdef extern from "foo.hpp":
  float * my_fun()

def my_other_fun():
  cdef float * foo = my_fun()
  del foo

When I try cython -a foo.pyx I get the error Deletion of non-Python, non-C++ object . 当我尝试cython -a foo.pyx我得到错误Deletion of non-Python, non-C++ object What gives? 是什么赋予了? Also if there's a way to accomplish this without having to allocate heap memory, I'm all ears. 如果有一种方法可以在不分配堆内存的情况下实现这一点,我全都听见了。

Memory should always be freed in the same way that it is allocated. 应始终以与分配内存相同的方式释放内存。 You are asking for trouble doing what you are doing. 你在做你正在做的事情时遇到麻烦。

Off hand I can think of two ways to address this problem: 我可以想到解决这个问题的两种方法:

1) Have a delete function in C++ that you call to free the memory. 1)在C ++中有一个删除函数,你调用它来释放内存。

2) Allocate the memory directly from a system service or library call (eg malloc) and use the corresponding function to free the memory. 2)直接从系统服务或库调用(例如malloc)分配内存,并使用相应的函数释放内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM