将字符串传递给c dll期望在python中使用const unsigned char *

时间:2015-08-19 11:34:56

标签: python c

我感到很遗憾,但我通常很难阅读ctypes文档...

如果我有一个带有const unsigned char *指针的C函数,并且我知道它既不会修改传入的字符串,也不会在函数调用之外保留对它的引用,那么传入指针真的很有意义直接到python字符串的字节。

我遵循了2方法

approach1:

cdll.func.restype=c_int
cdll.func.argtypes[c_int,c_int,c_int,c_char_p,c_int,c_char_p,c_int]
cdll.func(0,1,0,'11011101001111111000110011111',60,'0',80)

cdll function


 int func(inta,int b,int c, const unsigned char* cptr1 ,int ,const unsigned char* cptr2,int d){
       // do some string operation
       return 0;
    }

approach2:

v ='11011101001111111000110011111'
j = '0'
cdll.func(0,1,0,v,60,j,80)

  int func(inta,int b,int c, const unsigned char* cptr1 ,int ,const unsigned char* cptr2,int d){
       // do some string operation
       return 0;
    }

I done some research here link1

但它没有帮助,是不是真的要在python中做类型转换?但如果我这样做,它确实有效。提前致谢

1 个答案:

答案 0 :(得分:0)

以下是我从ctypes文件中得出的结论:

v = ctypes.create_string_buffer(b'11011101001111111000110011111')
j = ctypes.create_string_buffer(b'0')
cdll.func(0,1,0,v,60,j,80)

{3}} ctypes函数create_string_buffercreate_unicode_buffer未在Python 3中重命名/更改。因此create_string_buffer确实创建了一个字节缓冲区。

尝试传递u_chars:

def uchar_array(s):
    # construct array type of proper length including
    # zero-termination
    cls = ctypes.c_ubyte * (len(s)+1)

    # initialize with the provided bytes
    instance = cls(*list(s))

    # terminate with a zero
    instance[len(s)] = 0
    return instance

v = uchar_array(b'11011101001111111000110011111')
j = uchar_array(b'0')
cdll.func(0,1,0,v,60,j,80)