繁体   English   中英

使用ctypes在C中使用Python传递imgdata指针指向函数

[英]Python -passing imgdata pointer to a function in C using ctypes

我一直在尝试获取一个十六进制(unicode latin-1)值的imgdata字符串,该值是从Python通过指向imgdata的指针传递到我编写的C函数中的。 C函数会将蓝绿色,红色和Alpha这样的十六进制源值转换为灰度,然后将转换后的imgdata返回到dst指针地址。

当前,C函数输出的源值不正确,并且与imgdata中的十六进制值有很大不同。 关于将Python中的imgdata传递给C函数时我做错了什么的建议? 我的ctypes数据类型错误吗?

c函数的输出:src值:120 src值:212 src值:201 src值:1 src值:0 src值:0 src值:0 src值:0 src值:0 src值:0 src值:0 src值:0

值应为:4,8,20,0,1,7,12,0,6,7,14,0

Python代码:

#imgdata format is BGRA
imgdata = '\x04\x08\x14\x00\x01\x07\x0c\x00\x06\x07\x0e\x00'
testlib = ctypes.CDLL('path/to/my/lib/testlib.so')
source = (c_char_p * 12) (imgdata) 
destination = (c_uint8 * 12)()
testlib.grey.argtypes = (ctypes.c_void_p, ctypes.c_void_p,ctypes.c_int)
src = pointer(source)
dst = pointer(destination)
testlib.grey(dst,src,3)
p = ctypes.string_at(dst,12)
byte_array = map(ord, p)

C代码:

#include <stdio.h>
#include <stdint.h>

void grey(uint8_t *dst, uint8_t *sc, int num_pixels) {
    int k;
    for (k=0; k<12; k++)
    {
      printf("src values: %d ", *sc++);
    }
    // additional BGRA to Greyscale conversion code not shown

Python并不是您想要的那么难。 看起来有点像:

    imgdata = '\x04\x08\x14\x00\x01\x07\x0c\x00\x06\x07\x0e\x00'
    testlib = ctypes.CDLL('path/to/my/lib/testlib.so')
    dest = (c_uint8 * 12)()
    testlib.grey(dest, imgdata, 12)
    byte_array = bytearray(dest) # if you really neeed it

编辑 :阅读了对eryksun的评论进行了投票(由于他删除了它们,因此不相关)。 他解释了如何正确使用您的方法。

哦,好吧,他坚持,所以这是他的代码:

    imgdata = '\x04\x08\x14\x00\x01\x07\x0c\x00\x06\x07\x0e\x00'
    testlib = ctypes.CDLL('path/to/my/lib/testlib.so')
    dest = (ctypes.c_char * len(imgdata))()
    testlib.grey.restype = None
    testlib.grey.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int]
    testlib.grey(dest, imgdata, len(dest))
    byte_array = bytearray(dest) # or just use dest.raw which is a python str

和他的解释:

c_char_p是一个char*并且12个char指针的数组是不正确的,并且将指针传递给它是双重不正确的,并且它没有在ArgumentError死亡的唯一原因是argtypes中的c_void_p接受了很多内容而没有抱怨c_void_p整数和字符串,以及ctypes指针和数组。

暂无
暂无

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

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