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

标签 python c python-3.x numpy ctypes

我有一个简单的 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/

相关文章:

python - 将透明视频叠加到摄像机供稿OpenCV

python - 将数据从网络应用程序发送到 ipython 笔记本

python - 为什么这些数据类型比较相等但散列不同?

python - 用Python读取FTP文件内容并同时用于Pandas和直接使用

python-3.x - aiohttp - 套接字传输上的致命读取错误 - TimeoutError

python - 以任意倍数删除数组中的项目

c++ - 在 C++ 中以编程方式查找浮点寄存器的数量

c - 错误的输出 inet_ntop

c - 在 C 中使用标记串联访问和修改变量

python - 以 "rock&roll"模式打开文件