python ctypes-传递numpy数组-奇数输出 [英] python ctypes - passing numpy array - odd output
问题描述
我正在使用ctypes,并且正在将ndarray传递给c函数. 它给了我奇怪的输出行为. 这是一些代码:
I'm using ctypes and I'm passing a ndarray to a c-function. It gives me a odd output behavior. Heres some code:
C函数:
int foo(int * foo,int N){
for(int i=0;i<N;i++){
cout << "i " << i << " "<< foo[i] << endl;
}
return 0;
}
Python:
from ctypes import *
import numpy as np
bar = cdll.LoadLibrary(".../libtest.so")
N = c_int(10)
check = np.ones(10, dtype=int)
print check
bar.foo(c_int(check.ctypes.data),N)
输出:
[1 1 1 1 1 1 1 1 1 1]
i:0 out:1
i:1 out:0
i:2 out:1
i:3 out:0
i:4 out:1
i:5 out:0
i:6 out:1
i:7 out:0
i:8 out:1
i:9 out:0
应该没事吗? :)
我正在编译
g++ -g -c -fPIC -O0 pythagoras.cpp
g++ -shared -Wl,-soname=libtest.so -o libtest.so pythagoras.o
有人有什么想法吗?我现在正在搜索故障至少1个小时,而且我不知道解决方案是什么(可能有些愚蠢)
Anyone any ideas? I'm searching the failure now for at least 1hr and I'm having no idea what the solution is(probably something stupid)
提前谢谢!
推荐答案
将dtype
设置为Python int
将使用C long
.如果您使用的是64位平台(而不是Windows),则为64位数据类型,它解释了交错的0.您可以通过设置dtype=np.int32
与dtype=np.int64
进行检查.
Setting the dtype
to a Python int
will use a C long
. If you're on a 64-bit platform (other than Windows), that's a 64-bit data type, which explains the interleaved 0s. You can check this by setting dtype=np.int32
vs dtype=np.int64
.
第二,check.ctypes.data
是表示C void *
指针的Python int
.将其作为c_int
传递是不正确的.至少使用c_void_p
,然后定义argtypes
:
Secondly, check.ctypes.data
is a Python int
representing a C void *
pointer. Passing it as c_int
isn't correct. At a minimum, use c_void_p
, and define argtypes
:
from ctypes import *
import numpy as np
bar = CDLL('.../libtest.so')
bar.foo.argtypes = [c_void_p, c_int]
check.ctypes
定义_as_parameter_
ctypes挂钩,该挂钩返回c_void_p
的实例:
check.ctypes
defines the _as_parameter_
ctypes hook, which returns an instance of c_void_p
:
N = 10
check = np.ones(N, dtype=np.int32)
print check
bar.foo(check.ctypes, N)
您可以使用check.ctypes.data_as
或通过使用np.ctypeslib.ndpointer
定义类型来更具体.
You can be more specific with check.ctypes.data_as
, or by defining a type with np.ctypeslib.ndpointer
.
顺便说一句,foo
是C ++函数,而不是C.您必须使用extern "C"
.否则,将破坏导出的名称.
By the way, foo
is a C++ function, not C. You must have used extern "C"
. Otherwise the exported name would be mangled.
这篇关于python ctypes-传递numpy数组-奇数输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!