You don't seem to understand data structures. When you define a class, all you get back is a pointer. Storing that in psram would save you 4 bytes, with a huge penalty for moving it back and forth across the SPI bus. Store your
data in psram instead.
In this example I build a data structure to describe my individual elements, and then a class to hold a collection of those elements. The purpose of a class is having the methods available to the "this->" data (that's what object-oriented programming is about).
When you instantiate the small list (1000 elements), only 3000 bytes are needed. Since this is below the limit we have set for automatic psram allocation, it will use the SRAM. When we then request 100.000 elements, we need 300K, which is obviously more than we can get from the main heap, so it uses the psram. If you wanted to ensure that this always used psram, you could call ps_malloc instead of regular malloc.
Code: Select all
const char* fmtMemCk = "Free: %d\tMaxAlloc: %d\t PSFree: %d\n";
#define MEMCK Serial.printf(fmtMemCk,ESP.getFreeHeap(),ESP.getMaxAllocHeap(),ESP.getFreePsram())
typedef struct {
uint8_t red;
uint8_t blue;
uint8_t green;
} pixel;
class PsTest
{
public:
PsTest();
~PsTest();
bool begin(uint32_t elements);
bool end();
private:
uint32_t _elements;
pixel* _pixels;
};
PsTest::PsTest() : _elements(10000) {}
PsTest::~PsTest() {end();}
bool PsTest::end() {
if (_pixels) {
free(_pixels);
return true;
}
return false;
}
bool PsTest::begin(uint32_t elements) {
_elements = elements;
_pixels = (pixel*)malloc(_elements * sizeof(pixel));
if (!_pixels) {
log_d("Not enough memory to allocate %d elements", _elements);
return false;
}
memset(_pixels, 0, _elements * sizeof(pixel));
log_d("allocated %d elements", _elements);
return true;
}
PsTest ps_test;
void setup() {
Serial.begin(115200);
Serial.println();
MEMCK;
ps_test.begin(1000);
MEMCK;
ps_test.end();
MEMCK;
ps_test.begin(100000);
MEMCK;
}
void loop() {delay(-1);}