简体   繁体   中英

How do I create a reference to a C++ object from a C style pointer of an absolute address

We need to do a lot of operations on 8/16/32 bit (unsigned) integers stored in a complemented form. For this we have a template integer class with operators, and from this we get multiple classes with signed and unsigned 8/16/32 contents.

I:E: uint32_at , uint32_bt , int32_at , int32_bt etc. where each class instance has an internal variable val with the value.

We want to have constant arrays of such object, but if we define:

const uint32_bt table[4096] = { uint32_bt(5), uint32_bt(17), ... };

the compiler generates a constructor call for every element. An efficient compiler would generate 4 x 4096 = 16,384 bytes of flash. Our compiler generates about 100kB of flash and 16384 bytes of SRAM, since it calls a constructor to create every element.

One idea is to generate the table in C, and then create a C++ class for the complete table.

const uint32_t CTable[4096] = { ... };

and then create an instance of the table class passing the pointer and the size.

CPP_Table Table(4096, CTable);
   This initiates two internal variables
   tab = CTable
   size = 4096

The index operator would then return an object which is just a reference to something in the C Table.

uint32B operator [] (
const uint32B& operator [] (const uint32_t index) const
{
    return (somekindofcast)(&tab[size - index]);
}

So the question is, how do I cast an address so I can return a reference to an object?

const uint32_bt table[4096] = { uint32_at(5), uint32_at(17), ... };

the compiler generates a constructor call for every element.

Make uint32_at constructor constexpr . And make it an array of uint32_at .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM