Python:ctypes数据类型转换Python: ctypes 数据类型转换 python to ctypes
bytes to string
>>> b"abcde".decode("utf-8")
'abcde'
string to bytes
>>> "abcde".encode("utf-8")
b'abcde'
str to char *
string1 = "my string 1"
string2 = "my string 2"
# create byte objects from the strings
b_string1 = de('utf-8')
b_string2 = de('utf-8')
# send strings to c function
my_c_function(ctypes.c_char_p(b_string1),
ctypes.c_char_p(b_string2))
str to char is “b_string1 = de(‘utf-8’)”
create char* buffer
>>> from ctypes import *
>>> p = create_string_buffer(3)            # create a 3 byte buffer, initialized to NUL bytes
>>> print(sizeof(p), repr(p.raw))
3 b'\x00\x00\x00'
>>> p = create_string_buffer(b"Hello")    # create a buffer containing a NUL terminated string
>>> print(sizeof(p), repr(p.raw))
6 b'Hello\x00'
>>> print(repr(p.value))
b'Hello'
>>> p = create_string_buffer(b"Hello", 10) # create a 10 byte buffer
>>> print(sizeof(p), repr(p.raw))
10 b'Hello\x00\x00\x00\x00\x00'
python货币转换
>>> p.value = b"Hi"
>>> print(sizeof(p), repr(p.raw))
10 b'Hi\x00lo\x00\x00\x00\x00\x00'
>>>
通过多次尝试,我发现可以通过设置API的restype来获得正确的内存地址。
create_string_buffer(3) 是初始化 char 和 char * buffer