简体   繁体   中英

Copy python string characters to array.array (to be accessed later from C++)?

How can one copy python string characters to array.array ?

from array import array
b  = array('b', [0]*30)
s = 'abc'
# What should one do here to copy integer representation of 's' characters to 'b' ?

The integer representation of s characters should make sense to C++: ie if I convert the integers in b to C++ char string, I should get back "abc".

The best idea I have is below (but it would be good avoid explicit python loops):

for n,c in enumerate(s): b[n] = ord(c)

Thank you very much for your help!

try clearing it and filling it again:

for i in range(29,-1,-1):
    b.pop(i)
len0s = 29 - len(s)
s_lst = [*s]+['\0']+[0]*len0s
b.fromlist(s_lst)

should work if s is under 30 characters

array methods from https://pythongeeks.org/python-array-module/

You can do this if you have the 30-byte array populated ahead of time:

b = array('b', bytes(s, 'utf-8') + b[len(s):])

Or if you want to make it from scratch:

b = array('b', bytes(s, 'utf-8') + b'\0' * (30 - len(s)))

Or using the struct module:

struct.pack_into('30s', b, 0, bytes(s, 'utf-8'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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