Search code examples
mallocdirect3d11alignas

aligned_malloc() vs alignas() for Constant Buffers


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?


Solution

  • 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{};
    }