Skip to content

Commit 6279883

Browse files
committed
modstruct: Add one more extension to typecodes - 'S', a pointer to C string.
Also, add comment with description of extension to CPython's typecodes.
1 parent b55a59d commit 6279883

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

py/binary.c

+4-1
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626

2727
#include <stdint.h>
2828
#include <stdlib.h>
29+
#include <string.h>
2930
#include <assert.h>
3031

3132
#include "misc.h"
@@ -75,7 +76,7 @@ int mp_binary_get_size(char struct_type, char val_type, uint *palign) {
7576
case 'q': case 'Q':
7677
// TODO: This is for x86
7778
align = sizeof(int); size = sizeof(long long); break;
78-
case 'P': case 'O':
79+
case 'P': case 'O': case 'S':
7980
align = size = sizeof(void*); break;
8081
}
8182
}
@@ -161,6 +162,8 @@ mp_obj_t mp_binary_get_val(char struct_type, char val_type, byte **ptr) {
161162
*ptr += size;
162163
if (val_type == 'O') {
163164
return (mp_obj_t)val;
165+
} else if (val_type == 'S') {
166+
return mp_obj_new_str((char*)val, strlen((char*)val), false);
164167
} else if (is_signed(val_type)) {
165168
return mp_obj_new_int(val);
166169
} else {

py/modstruct.c

+16
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,22 @@
3939

4040
#if MICROPY_PY_STRUCT
4141

42+
/*
43+
This module implements most of character typecodes from CPython, with
44+
some extensions:
45+
46+
O - (Pointer to) an arbitrary Python object. This is useful for callback
47+
data, etc. Note that you must keep reference to passed object in
48+
your Python application, otherwise it may be garbage-collected,
49+
and then when you get back this value from callback it may be
50+
invalid (and lead to crash).
51+
S - Pointer to a string (returned as a Python string). Note the
52+
difference from "Ns", - the latter says "in this place of structure
53+
is character data of up to N bytes length", while "S" means
54+
"in this place of a structure is a pointer to zero-terminated
55+
character data".
56+
*/
57+
4258
STATIC char get_fmt_type(const char **fmt) {
4359
char t = **fmt;
4460
switch (t) {

0 commit comments

Comments
 (0)