这是我从dll函数的一个例子。我知道我应该忽略返回值,但是如何在Python中声明数组以获得新的数组呢?在
C++代码:
extern "C" _declspec(dllexport) int* SortFunc(int arr[], int n)
{
for(int i = 1; i < n; i++)
for(int j = i; j > 0 && arr[j-1] > arr[j]; j--)
{
int temp = arr[j - 1];
arr[j - 1] = arr[j];
arr[j] = temp;
}
return arr;
}
我想在Python程序中使用这个函数。如果我把数组传递给函数,通常的描述是有效的,但是如果想取回它就不行了。在
^{pr2}$当我使用它时,我可以看到一个错误:“int”object is not subscribable”,数组b与数组a具有相同的描述
我不确定是什么原因导致你看到这个错误,尽管我怀疑“b”是怎么产生的。我假设您的函数有一个稍微不同的Python版本,因为Python的语法不允许“for(inti=0…”)语法。在
也就是说,我能够从下面的C函数的Python实现中得到一个正确排序的数组:
运行时使用
^{pr2}$作为输入,给出从调用“print(b[:])”中排序的数组[1,2,3,4,6,10]。在
作为补充说明,您可以通过简单地调用“sorted(a)”来获得相同的结果,据我所知,它将与您编写的函数起到相同的作用。在
看起来
SortFunc
在适当的地方修改了arr
。这行吗?在我认为对于您当前的代码,
^{pr2}$b
可能只是一个int,也许是一个错误标志。您可能需要使用passbyreference获取结果,而不是返回结果。因此Python代码如下:这将调用
void SortFunc(int arr[], int sorted[], int n)
。在http://staff.mbi-berlin.de/schultz/Call_C-DLL_from_Python.txt处有一些代码通过引用更改数组。在还有一件事:我不确定这是否有效,但是您可以尝试返回一个新分配的数组,而不是返回
arr
:相关问题 更多 >
编程相关推荐