Can you assign one nvs_handle_t to the other?

A6ESPF
Posts: 28
Joined: Tue Dec 10, 2019 12:16 pm

Can you assign one nvs_handle_t to the other?

Postby A6ESPF » Fri Dec 23, 2022 12:08 pm

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?

User avatar
mbratch
Posts: 303
Joined: Fri Jun 11, 2021 1:51 pm

Re: Can you assign one nvs_handle_t to the other?

Postby mbratch » Fri Dec 23, 2022 3:00 pm

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.

Who is online

Users browsing this forum: Baidu [Spider] and 77 guests