gpt4 book ai didi

python ctypes 返回零作为数组中的第一个元素?

转载 作者:太空宇宙 更新时间:2023-11-03 23:59:17 25 4
gpt4 key购买 nike

我有一个简单的 python 脚本,它使用 ctypes 将数组指针传递给外部函数。然后外部函数只是将相同的数组传递回 python(这意味着作为一个简单的单元测试以确保 python 和外部函数都使用相同的值)。函数原型(prototype)如下所示:

void Array_tmp(int32_t Array[], int32_t *len, int32_t Array2[])

python 脚本如下所示:

from ctypes import *
import numpy as np
import numpy.ctypeslib
import os

dll = 'array_test.dll'

loadlib = cdll.LoadLibrary(dll)

arr = np.array([1,2,3,4,5])
length = len(arr)

c_arr = np.ctypeslib.as_ctypes(arr)
clen = c_int32(length)
p_clen = pointer(clen)
c_arr_ptr = cast(c_arr, POINTER(c_double))
loadlib.Array_tmp.argtypes = [type(c_arr_ptr), type(p_clen)]
loadlib.Array_tmp.restype = type(c_arr)

g = loadlib.Array_tmp(c_arr_ptr, p_clen)
print(g)
np_arr_g = np.ctypeslib.as_array(g)
print(np_arr_g)

脚本的输出如下所示:

<numpy.ctypeslib.c_long_Array_5 object at 0x044A7AD0>
[0 2 3 4 5]

为什么数组的第一个元素显示为零而不是一个,而其他所有元素都是正确的?

编辑:将 c_arr_ptr = cast(c_arr, POINTER(c_double)) 行更改为 c_arr_ptr = cast(c_arr, POINTER(c_int32)) 对除了内存地址的轻微变化之外的输出。

最佳答案

所提供的代码存在很多问题。这是一个工作示例:

测试.c

#include <memory.h>
#include <inttypes.h>

#define API __declspec(dllexport) /* Windows-specific export */

/* FYI: No reason for 'len' to be a pointer */
API void Array_tmp(int32_t Array[], int32_t *len, int32_t Array2[])
{
memcpy(Array2,Array,*len * sizeof(int32_t));
}

测试.py

from ctypes import *
import numpy as np

dll = CDLL('test')

# Good idea to declare the functions arguments and return type fully for error checking.
func = dll.Array_tmp
func.argtypes = POINTER(c_int32),POINTER(c_int32),POINTER(c_int32)
func.restype = None

# Create input array and output array of same size.
arr = np.array([1,2,3,4,5])
out_arr = np.zeros(arr.shape,dtype=np.int32)

# Get everything as a ctypes object
c_arr = np.ctypeslib.as_ctypes(arr)
c_out_arr = np.ctypeslib.as_ctypes(out_arr)
clen = c_int32(len(arr))

func(c_arr,byref(clen),c_out_arr)

# Original output array of zeros is now modified
print(out_arr)

输出:

[1 2 3 4 5]

关于python ctypes 返回零作为数组中的第一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51308189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com