2.5999999046325684
3.对于字符串char* ,在声明传⼊参数类型时,需要声明为字符指针,然后分配⼀块char数组,最后把这个数组强制转换为字符指针并且,在把python脚本中的数据结构导⼊c++中时,需要把str转换为bytes或者bytesarray类型,并且进⾏迭代器分解
hello=dll.HelloWorld
hello.argtypes=[POINTER(c_char)] #传⼊参数为字符指针
STR=(c_char * 100)(*bytes(\"相信你还在这⾥\",'utf-8')) #把⼀组100个的字符定义为STRcast(STR, POINTER(c_char))hello(STR)
输出:
相信你还在这⾥
4.对于其他数据类型的数组,(例如int*),操作相似:
Ints=dll.Ints
Ints.argtypes=[POINTER(c_int),c_int]
INT=(c_int * 100)(*[1,2,3]) #把列表传⼊变长参数args*中cast(INT, POINTER(c_int))Ints(INT,c_int(3))
输出:
1 2 3
5.对于返回值为数组的情况,可以直接使⽤索引去访问,但是下标操作[]不是从迭代器中取对象,⽽是地址偏移:
def fillHoleCpp(im):
dll = cdll.LoadLibrary(\"bfs.dll\") bfs=dll.bfs
bfs.argtypes = [POINTER(c_int),c_int] bfs.restype = POINTER(c_int)
a = np.asarray(range(16), dtype=np.int32).reshape([4, 4]) if not a.flags['C_CONTIGUOUS']:
a = np.ascontiguous(a, dtype=a.dtype) # 如果不是C连续的内存,必须强制转换
IMG = cast(a.ctypes.data, POINTER(c_int)) # 转换为ctypes,这⾥转换后的可以直接利⽤cty cast(IMG, POINTER(c_int)) length=a.size
ans=bfs(IMG,c_int(length)) print(type(ans))
for i in range(0,length): print(ans[i],end=' ')