我使用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;''') 10However 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: 1I 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 RAll 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更多推荐
发布评论