In C++, we have the keyword alignas(n)
and we have the _aligned_malloc(m,n)
function.
alignas
works on the type while aligned_malloc
works on whatever you call it.
Can I use alignas(16)
to fullfil the 16-byte alignment requirement for Direct3D Constant Buffers?
Asked
Active
Viewed 322 times
2

Raildex
- 3,406
- 1
- 18
- 42
1 Answers
2
Yes, you could use it like this:
struct SceneConstantBuffer
{
alignas(16) DirectX::XMFLOAT4X4 ViewProjection[2];
alignas(16) DirectX::XMFLOAT4 EyePosition[2];
alignas(16) DirectX::XMFLOAT3 LightDirection{};
alignas(16) DirectX::XMFLOAT3 LightDiffuseColor{};
alignas(16) int NumSpecularMipLevels{ 1 };
};
What won't work is __declspec(align)
...
EDIT: If you want to use it on the struct itself something similar to this should work too:
struct alignas(16) SceneConstantBuffer
{
DirectX::XMMATRIX ViewProjection; // 16-bytes
...
DirectX::XMFLOAT3 LightDiffuseColor{};
}

l'L'l
- 44,951
- 10
- 95
- 146
-
Can I use `alignas(16)` on `SceneConstantBuffer` or do i have to use it on every member? – Raildex Jan 18 '20 at 08:27
-
@Raildex: Yes, see edit. You'll want to check it though when you initialize it with an assert. – l'L'l Jan 18 '20 at 08:42
-
Thank you! One more question: Do the members of a constant buffer need to be aligned or only the constant buffer itself? – Raildex Jan 18 '20 at 09:48
-
1@Raildex: Yes, there still needs to be alignment, so often padding is used to make up for the difference if needed. Check [this answer](https://stackoverflow.com/a/21150698/499581), it should be able to give you some idea what is at work, cheers! – l'L'l Jan 22 '20 at 16:15