4
\$\begingroup\$

I just finished my first DirectX 11 program. But I have several questions on memory transfer between CPU and GPU.

In my program, I create a vertex buffer first:

bool InitializeGeometry() {
    VertexType vertices[] = {
        XMFLOAT3(0.0f, 0.0f, 0.5f),
        XMFLOAT3(0.5f, 0.0f, 0.5f),
        XMFLOAT3(0.0f, 0.5f, 0.5f)
    };

    D3D11_BUFFER_DESC vbDesc;
    ZeroMemory(&vbDesc, sizeof(vbDesc));
    vbDesc.Usage = D3D11_USAGE_IMMUTABLE;
    vbDesc.ByteWidth = sizeof(vertices);
    vbDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    vbDesc.CPUAccessFlags = 0;

    D3D11_SUBRESOURCE_DATA vbData;
    ZeroMemory(&vbData, sizeof(vbData));
    vbData.pSysMem = vertices;

    if (FAILED(gDevice->CreateBuffer(&vbDesc, &vbData, &gVB)))
        return false;

    // ...
}

Later I will use this vertex buffer for rendering. Note that the vertices array is a stack variable and it will be destroyed on after the return of InitializeGeometry.

Does actual memory transfer from CPU to GPU happen in CreateBuffer? Or CreateBuffer just takes a reference to the vertices so I should give a longer lifetime to the vertices?

If the transfer does starts in CreateBuffer(or Unmap for dynamic buffers), can I expect the GPU driver save a copy of my vertices? I am afraid that the transfer takes so much time that InitializeGeometry function returns early, hence leaves transferring data incomplete.

\$\endgroup\$
2
  • \$\begingroup\$ It is certainly safe to discard the buffer after the API call returns. I can't say this with certainty, but I assume the user has no control over when the driver will actually transfer data to the device. More than likely it will keep system memory copies of your data, in a any case. \$\endgroup\$
    – glampert
    Sep 18, 2015 at 17:42
  • \$\begingroup\$ @glampert Yes, I agree with you that the user has no control over when the driver will actually transfer data to the device. But I think knowing the mechanism helps me to decide the lifetime of my data in the CPU side. \$\endgroup\$ Sep 18, 2015 at 17:51

1 Answer 1

2
\$\begingroup\$

All the functions that take a lump of data like CreateBuffer, CreateVertexShader and others, they copy/interpret the data before the function returns.

As soon as it returns, you do not need to keep the data alive anymore.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .