从scipy的weave.inline返回C数组到python范围(Returning C arrays into python scope from scipy's weave.inlin

编程入门 行业动态 更新时间:2024-10-25 10:21:14
从scipy的weave.inline返回C数组到python范围(Returning C arrays into python scope from scipy's weave.inline)

我使用scipy的weave.inline来执行计算上昂贵的任务。 我有问题将一维数组返回到python范围。 Weave.inline使用一个名为“return_val”的特殊参数,用于将值返回到python范围。 以下返回整数值的示例运行良好:

>>> from scipy.weave import inline >>> print inline(r'''int N = 10; return_val = N;''') 10

但是,以下示例确实在没有提示错误的情况下进行编译,并不会返回我期望的数组:

>>> from scipy.weave import inline >>> code =\ r''' int* pairs; int lenght = 0; for (int i=0;i<N;i++){ lenght += 1; pairs = (int *)malloc(sizeof(int)*lenght); pairs[i] = i; std::cout << pairs[i] << std::endl; } return_val = pairs; ''' >>> N = 5 >>> R = inline(code,['N']) >>> print "RETURN_VAL:",R 0 1 2 3 4 RETURN_VAL: 1

我需要动态地重新分配数组“对”的大小,这就是为什么我本身无法传递numpy.array或python列表的原因。

I am using scipy's weave.inline to perform computationally expensive tasks. I have problems returning an one-dimensional array back into the python scope. Weave.inline uses a special argument called "return_val" for the purpose of returning values back into the python scope. The following example returning an integer value works well:

>>> from scipy.weave import inline >>> print inline(r'''int N = 10; return_val = N;''') 10

However the following example, which indeed compiles without prompting an error, does not return the array i would expect:

>>> from scipy.weave import inline >>> code =\ r''' int* pairs; int lenght = 0; for (int i=0;i<N;i++){ lenght += 1; pairs = (int *)malloc(sizeof(int)*lenght); pairs[i] = i; std::cout << pairs[i] << std::endl; } return_val = pairs; ''' >>> N = 5 >>> R = inline(code,['N']) >>> print "RETURN_VAL:",R 0 1 2 3 4 RETURN_VAL: 1

I need to reallocate the size of the array "pairs" dynamically which is why I can't pass a numpy.array or python list per se.

最满意答案

您需要做的就是使用原始的python c-api调用 ,或者如果您正在寻找更方便的东西,内置的scipy编织包装器。

不保证泄漏或效率,但它应该看起来像这样:

from scipy.weave import inline code = r''' py::list ret; for(int i = 0; i < N; i++) { py::list item; for(int j = 0; j < i; j++) { item.append(j); } ret.append(item); } return_val = ret; ''' N = 5 R = inline(code,['N']) print R

All you need to do is use the raw python c-api calls, or if you're looking for something a bit more convenient, the built in scipy weave wrappers.

No guarantees about leaks or efficiency, but it should look something a bit like this:

from scipy.weave import inline code = r''' py::list ret; for(int i = 0; i < N; i++) { py::list item; for(int j = 0; j < i; j++) { item.append(j); } ret.append(item); } return_val = ret; ''' N = 5 R = inline(code,['N']) print R

更多推荐

本文发布于:2023-07-05 15:50:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1039140.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   inline   weave   scipy   scope

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!