You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将ctypes调用C函数返回的指针转换为numpy uint32数组

问题解决步骤

你遇到的报错本质是np.ctypeslib.as_array无法直接解析无类型的c_void_p指针,需要先手动指定指针指向的数据类型,同时要把c_int类型的长度转为Python原生整数。

正确转换代码

# 提取长度的实际整数值
arr_len = length.value
# 将无类型void指针强转为指向uint32类型的指针
typed_ptr = cast(data, POINTER(c_uint32))
# 生成numpy数组,不拷贝内存直接复用C侧分配的空间
uint_arr = np.ctypeslib.as_array(typed_ptr, shape=(arr_len,))

执行后uint_arr就是你需要的np.uint32类型数组,直接打印可以看到C侧写入的1~10的测试值:

array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10], dtype=uint32)

注意事项

上述生成的numpy数组直接复用C侧malloc的内存,numpy不会自动管理这部分内存的释放,用完后需要手动调用C侧的free接口避免内存泄漏。你可以在C库中补充对应的释放函数:

// c_lib.c新增代码
void free_uint_array(unsigned int *data) {
    free(data);
}

Python侧调用释放:

test.free_uint_array.argtypes = [c_void_p]
test.free_uint_array(data)

内容的提问来源于stack exchange,提问作者M.E.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 09:45:00