简体   繁体   English

python ctypes - 传递numpy数组 - 奇数输出

[英]python ctypes - passing numpy array - odd output

I'm using ctypes and I'm passing a ndarray to a c-function. 我正在使用ctypes,我正在将一个ndarray传递给一个c函数。 It gives me a odd output behavior. 它给了我奇怪的输出行为。 Heres some code: 下面是一些代码:

C-Function: 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)

Output: 输出:

[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

Should be all ones right? 一切都对吗? :) :)

I' compiling with 我正在编译

g++ -g -c -fPIC -O0  pythagoras.cpp 
g++ -shared -Wl,-soname=libtest.so -o libtest.so  pythagoras.o 

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) 我现在正在寻找失败至少1小时,我不知道解决方案是什么(可能是一些愚蠢的事情)

Thanks in advance! 提前致谢!

Setting the dtype to a Python int will use a C long . dtype设置为Python int将使用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. 如果您使用的是64位平台(Windows除外),那么这是一种64位数据类型,它解释了交错的0。 You can check this by setting dtype=np.int32 vs dtype=np.int64 . 您可以通过设置dtype=np.int32 vs dtype=np.int64 dtype=np.int32来检查这dtype=np.int64

Secondly, check.ctypes.data is a Python int representing a C void * pointer. 其次, check.ctypes.data是一个表示C void *指针的Python int Passing it as c_int isn't correct. 将其作为c_int传递是不正确的。 At a minimum, use c_void_p , and define argtypes : 至少,使用c_void_p ,并定义argtypes

from ctypes import *
import numpy as np

bar = CDLL('.../libtest.so')
bar.foo.argtypes = [c_void_p, c_int]

check.ctypes defines the _as_parameter_ ctypes hook, which returns an instance of c_void_p : check.ctypes定义_as_parameter_ ctypes钩子,它返回c_void_p一个实例:

N = 10
check = np.ones(N, dtype=np.int32)
print check
bar.foo(check.ctypes, N)

You can be more specific with check.ctypes.data_as , or by defining a type with np.ctypeslib.ndpointer . 您可以更具体用check.ctypes.data_as ,或通过定义一个类型np.ctypeslib.ndpointer

By the way, foo is a C++ function, not C. You must have used extern "C" . 顺便说一句, foo是一个C ++函数,而不是C.你必须使用extern "C" Otherwise the exported name would be mangled. 否则导出的名称将被破坏。

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

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