内存分配

确定好使用的内存类型后,我们可以填写VkMemoryAllocateInfo结构体来分配需要的内存:

VkMemoryAllocateInfo allocInfo = {};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = memRequirements.size;
allocInfo.memoryTypeIndex = findMemoryTyp(memRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);

内存分配只需要填写好需要的内存大小和内存类型,然后调用vkAllocateMemory函数分配内存即可:

VkBuffer vertexBuffer;
VkDeviceMemory vertexBufferMemory;

        ...

if (vkAllocateMemory(device, &allocInfo, nullptr, &vertexBufferMemory) != VK_SUCCESS) {
    throw std::runtime_error("failed to allocate vertex buffer memory!");
}

如果内存分配成功,我们就可以使用vkBindBufferMemory函数将分配的内存和缓冲对象进行关联:

vkBindBufferMemory(device, vertexBuffer, vertexBufferMemory, 0);

vkBindBufferMemory函数的前三个参数非常直白,第四个参数是偏移值。这里我们将内存用作顶点缓冲,可以将其设置为0。偏移值需要满足能够被memRequirements.alignment整除。

和C++的动态内存分配一样,这里分配的内存需要我们自己进行释放。通常我们在缓冲不再使用时,释放它所关联的内存:

void cleanup() {
cleanupSwapChain();

    vkDestroyBuffer(device, vertexBuffer, nullptr);
    vkFreeMemory(device, vertexBufferMemory, nullptr);