Print string C in Python

I want to print a C string using a Python statement print. The array vendorNamecomprises a line ASCIIZ C A ANTHONY & SONS INC. My motivation is to convert the C string to a Python string so that I can use all the methods of the Python string.

I have a structure:

class _vendrRecord(Structure):
    _pack_ = 1                                            # pack the struct
    _fields_ = [
        ("vendorName"            ,c_ubyte *(40 + 1)),
        ("ytdPayments"           ,c_ulong),
        ]

I want to print the string "vendorName", which is ASCIIZ.

I can print it using printf as follows:

printf(b"%s\n", vendrRecord.vendorName)

I tried this one print(vendrRecord.vendorName), but it just prints the address. Based on information from Jamie Nicole-Shelley, I tried print(cast(vendrRecord.vendorName,c_char_p).value), but it does b'A ANTHONY & SONS INC'. I want justA ANTHONY & SONS INC

Please note that print(vendrRecord.ytdPayments)prints correctly.

+4
source share
2 answers

, . bytes:

>>> v.vendorName
<__main__.c_ubyte_Array_41 object at 0xb0994a04>
>>> cast(v.vendorName, c_char_p)
c_char_p(176882328)
>>> cast(v.vendorName, c_char_p).value
b'A ANTHONY & SONS INC'

bytes - , , - , . :

>>> cast(v.vendorName, c_char_p).value[7]
78

, ascii, Python, :

>>> s = cast(v.vendorName, c_char_p).value.decode("ascii")
>>> s
'A ANTHONY & SONS INC'
>>> type(s)
<class 'str'>
>>> s.lower()
'a anthony & sons inc'
+3

, , . , , ,

print(), , ++

+1

Source: https://habr.com/ru/post/1623588/


All Articles