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?
1 Answer
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{}; } 4 Comments
Raildex
Can I use
alignas(16) on SceneConstantBuffer or do i have to use it on every member?l'L'l
@Raildex: Yes, see edit. You'll want to check it though when you initialize it with an assert.
Raildex
Thank you! One more question: Do the members of a constant buffer need to be aligned or only the constant buffer itself?
l'L'l
@Raildex: Yes, there still needs to be alignment, so often padding is used to make up for the difference if needed. Check this answer, it should be able to give you some idea what is at work, cheers!