I'm seeing weird behavior trying to combine C++ and C code. I'm using a C++ class within C code, using static_cast
with a void*
to the class. This is done in the following way.
//C++ code
typedef void* CSPI;
CSPI newCSPI() {
return static_cast<CSPI>(new XSpi);
}
This function is declared in the header as follows.
//C++ code
extern "C" CSPI newCSPI(void);
I can then call the C++ functions in the C code. An example of the implementation of the other functions is seen below.
//C++ code
void selectCSlave(void* Cspi) {
static_cast<SPI*>(Cspi)->selectSlave();
}
This function is also declared as extern "C"
in the header.
This casting function is implemented as follows.
//C++ code
void SPI::selectSlave(void) {
// Select the slave by setting the slave select to low
XGpio_DiscreteWrite(&slaveSelectDevice, 1, 0x00);
}
I'm trying to execute the following block of code. It all succeeds except for the very last line.
//C code
u8 junk, waitstate = 0xff;
/* Select device. */
selectCSlave(spi);
/* Write address and command to device. */
esc_address(address, ESC_CMD_READWS, (uint16_t *) tALevent);
/*transfering the wait-state byte*/
transferC(spi, &waitstate, &junk,1);
/* Here we want to read data and keep MOSI low (0x00) during
* all bytes except the last one where we want to pull it high (0xFF).
* Read (and write termination bytes).
*/
transferC(spi, read_termination + (sizeof(read_termination) - len),
(uint8_t *) buf, len);
/* Un-select device. */
deselectCSlave(spi);
During the deselectCSlave(spi)
call, the pointer somehow changes value. Inside the cast function, the pointer still has the same value. Inside the function it is cast to, the value changes. The implementation is exactly the same as selectSlave()
, which does work.
I can't see why the value would suddenly change. What am I missing here?
Aucun commentaire:
Enregistrer un commentaire