Skip to content

Commit 25eb980

Browse files
committed
Only mark unaligned types in buffers
Previously all types are marked unaligned in buffer format strings, now we test for alignment before adding the '=' marker.
1 parent 425b497 commit 25eb980

File tree

2 files changed

+12
-8
lines changed

2 files changed

+12
-8
lines changed

include/pybind11/numpy.h

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -686,6 +686,7 @@ struct field_descriptor {
686686
const char *name;
687687
size_t offset;
688688
size_t size;
689+
size_t alignment;
689690
std::string format;
690691
dtype descr;
691692
};
@@ -727,7 +728,9 @@ inline PYBIND11_NOINLINE void register_structured_dtype(
727728
if (field.offset > offset)
728729
oss << (field.offset - offset) << 'x';
729730
// note that '=' is required to cover the case of unaligned fields
730-
oss << '=' << field.format << ':' << field.name << ':';
731+
if (field.offset % field.alignment)
732+
oss << '=';
733+
oss << field.format << ':' << field.name << ':';
731734
offset = field.offset + field.size;
732735
}
733736
if (itemsize > offset)
@@ -787,6 +790,7 @@ struct npy_format_descriptor<T, enable_if_t<is_pod_struct<T>::value>> {
787790
#define PYBIND11_FIELD_DESCRIPTOR_EX(T, Field, Name) \
788791
::pybind11::detail::field_descriptor { \
789792
Name, offsetof(T, Field), sizeof(decltype(std::declval<T>().Field)), \
793+
std::alignment_of<decltype(std::declval<T>().Field)>::value, \
790794
::pybind11::format_descriptor<decltype(std::declval<T>().Field)>::format(), \
791795
::pybind11::detail::npy_format_descriptor<decltype(std::declval<T>().Field)>::dtype() \
792796
}

tests/test_numpy_dtypes.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -30,13 +30,13 @@ def test_format_descriptors():
3030
assert re.match('^NumPy type info missing for .*UnboundStruct.*$', str(excinfo.value))
3131

3232
assert print_format_descriptors() == [
33-
"T{=?:x:3x=I:y:=f:z:}",
34-
"T{=?:x:=I:y:=f:z:}",
35-
"T{=T{=?:x:3x=I:y:=f:z:}:a:=T{=?:x:=I:y:=f:z:}:b:}",
36-
"T{=?:x:3x=I:y:=f:z:12x}",
37-
"T{8x=T{=?:x:3x=I:y:=f:z:12x}:a:8x}",
38-
"T{=3s:a:=3s:b:}",
39-
'T{=q:e1:=B:e2:}'
33+
"T{?:x:3xI:y:f:z:}",
34+
"T{?:x:=I:y:=f:z:}",
35+
"T{T{?:x:3xI:y:f:z:}:a:T{?:x:=I:y:=f:z:}:b:}",
36+
"T{?:x:3xI:y:f:z:12x}",
37+
"T{8xT{?:x:3xI:y:f:z:12x}:a:8x}",
38+
"T{3s:a:3s:b:}",
39+
'T{q:e1:B:e2:}'
4040
]
4141

4242

0 commit comments

Comments
 (0)