简体   繁体   English

将 python 字符串字符复制到 array.array(稍后从 C++ 访问)?

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

How can one copy python string characters to array.array ?如何将 python 字符串字符复制到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". s字符的整数表示对于 C++ 应该有意义:即如果我将b中的整数转换为 C++ char字符串,我应该得到“abc”。

The best idea I have is below (but it would be good avoid explicit python loops):我最好的想法如下(但最好避免显式的 python 循环):

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如果 s 少于 30 个字符应该可以工作

array methods from https://pythongeeks.org/python-array-module/来自https://pythongeeks.org/python-array-module/的数组方法

You can do this if you have the 30-byte array populated ahead of time:如果您提前填充了 30 字节的数组,则可以执行此操作:

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模块:

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

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

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