11.5.4 An External Example
This example implements, using external memory, addressable bit memory.
In this case each bit is stored in real data memory, not off chip. The code defines an
external
memory of 512 units and map accesses using the appropriate
read and write function to one of 64 bytes in local data memory.
First the external memory is defined:
extern unsigned int bit_memory
__attribute__((space(external(size(512)))));
Next appropriate read and write functions are defined. These functions will make use of an array of memory that is reserved in the normal way.
static unsigned char real_bit_memory[64];
unsigned char __read_external8(unsigned int address,
unsigned int memory_space) {
if (memory_space == bit_memory) {
/* an address within our bit memory */
unsigned int byte_offset, bit_offset;
byte_offset = address / 8;
bit_offset = address % 8;
return (real_bit_memory[byte_offset] >> bit_offset) & 0x1;
} else {
fprintf(stderr,"I don't know how to access memory space: %d\n",
memory_space);
}
return 0;
}
void __write_external8(unsigned int address,
unsigned int memory_space,
unsigned char data) {
if (memory_space == bit_memory) {
/* an address within our bit memory */
unsigned int byte_offset, bit_offset;
byte_offset = address / 8;
bit_offset = address % 8;
real_bit_memory[byte_offset] &= (~(1 << bit_offset));
if (data & 0x1) real_bit_memory[byte_offset] |=
(1 << bit_offset);
} else {
fprintf(stderr,"I don't know how to access memory space: %d\n",
memory_space);
}
}
These functions work in a similar fashion:
- if accessing
bit_memory
, then- determine the correct byte offset and bit offset
- read or write the appropriate place in the
real_bit_memory
- otherwise access another memory (whose access is unknown)
With the two major pieces of the puzzle in place, generate some variables and accesses:
__external__ unsigned char bits[NUMBER_OF_BITS]
__attribute__((space(external(bit_memory))));
// inside main
__external__ unsigned char *bit;
bit = bits;
for (i = 0; i < 512; i++) {
printf("%d ",*bit++);
}
Apart from the __external__
CV-qualifiers, ordinary C
statements can be used to define and access variables in the external memory space.