Page 1 of 1

Can you assign one nvs_handle_t to the other?

Posted: Fri Dec 23, 2022 12:08 pm
by A6ESPF
In my application, I have a function which opens an NVS partition, a function which does some writing and a function which closes the NVS partition. Since the same nvs_handle_t can't be opened again after closing it, what I do currently is create a local nvs_handle_t which I use for nvs_open(), and after it's opened, I assign it to the global nvs_handle_t, like this:

Code: Select all

nvs_handle_t g_nvs_hndl;

esp_err_t open_internal(void)
{
    nvs_handle_t nvs_hndl;
    esp_err_t err = nvs_open("nvs", NVS_READWRITE, &nvs_hndl);
    
    if (ESP_OK == esp_err)
    {
        g_nvs_hndl = nvs_hndl;
    }
    
    return err;
}
I then use the global nvs_handle_t for closing the partition:

Code: Select all

void close_internal(void)
{
    nvs_close(g_nvs_hndl);
}
When I look at the definition of nvs_handle_t, I see that it's a plain uint32_t number, so I thought that assignment like this shouldn't be a problem. Am I right?

Re: Can you assign one nvs_handle_t to the other?

Posted: Fri Dec 23, 2022 3:00 pm
by mbratch
A6ESPF wrote:
Fri Dec 23, 2022 12:08 pm
When I look at the definition of nvs_handle_t, I see that it's a plain uint32_t number, so I thought that assignment like this shouldn't be a problem. Am I right?
There is no problem assigning it. It's a simple type.

As far as managing NVS handles, it's really no different than if you were managing a file handle. You can have multiple handles open on the same set of data. You can open a file for reading multiple times as long as you keep track of the individual handles and close all of them when you're done. You just have to be careful about simultaneous writing if you have it open for read/write.