New DRAM_ATTR outside of definition [-Wattributes]

Is it possible to create an object instance in IRAM? For example:

struct A {
    int a;
    int b;
};
struct A *p = new DRAM_ATTR A;

does not compile as expected:

warning: ignoring attributes applied to class type 'A' outside of definition [-Wattributes]

Thank you.

In the ESP-IDF framework, you can allocate an object in IRAM using the IRAM_ATTR attribute. Your code would look something like this:

#include "esp_attr.h"

struct A {
    int a;
    int b;
};

struct A *p = IRAM_ATTR new A;

The IRAM_ATTR attribute is used to place the object in IRAM (Internal RAM), which is a section of RAM that is faster but smaller compared to DRAM. This is a commonly used technique in ESP-IDF to allocate certain data structures in IRAM to improve performance for real-time or critical code.

Make sure to include #include "esp_attr.h" to use the IRAM_ATTR attribute. Also, note that new is not a standard C or C++ keyword, so it must be defined in your project or library.

This should help you allocate an instance of your struct in IRAM successfully.

Thank you, but with placing IRAM_ATTR in front of new keyword, the code does not compile at all (error "in expansion of macro 'IRAM_ATTR'"). Placing it after the new keyword produces exactly the same result as DRAM_ATTR.

New keyword creates a new object instance. Normally on the heap but I need to place it in IRAM ...

I apologize for any confusion. You are correct; you cannot directly use the IRAM_ATTR attribute in front of the new keyword to allocate objects in IRAM in ESP-IDF. The new operator is part of C++ and typically allocates objects on the heap, not in specific memory regions like IRAM.

To allocate objects in IRAM, you would need to use other techniques. For example, you can allocate memory in IRAM using functions like heap_caps_malloc with the MALLOC_CAP_INTERNAL flag and then construct your object within that memory. Here's an example of how you could do it:

#include "esp_heap_caps.h"

struct A {
    int a;
    int b;
};

A *p = (A*)heap_caps_malloc(sizeof(A), MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);

if (p) {
    // Initialize your object here
    p->a = 1;
    p->b = 2;
    
    // Your object is now allocated in IRAM
} else {
    // Handle allocation failure
}

This code uses heap_caps_malloc to allocate memory in the IRAM and then manually initializes your object within that memory. Don't forget to free the memory when you're done using heap_caps_free.

Again, I apologize. I hope this helps.

This seems to work. I'll try changing my project the way you proposed.

Thank you!

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.