Search code examples
c++ccastingsignedunsigned-char

Change uint8_t* to char*?


I have an API which requests a char*, this is my API function:

CANMessage(unsigned _id,  const char* _data, char _len = 8)

More information available here: https://os.mbed.com/docs/mbed-os/v5.11/mbed-os-api-doxy/classmbed_1_1_c_a_n_message.html

I would like to call this function from within another function, but I am getting confused about const char* and casting. I want to call this function from function foo(), like so:

void foo(unsigned int id, /*???*/ data, char len) {
    CANMessage(id, data, len)
}

So I need to pass id, data and len to function foo. My problem is that the data coming in is a uint8_t type. I got a vector of uint8_t, where the address of the first element is the one I need to pass:

vector<uint8_t> dta;

Which I tried to pass as &dta[0]: foo(idNo, &dta[0], length)

With the foo function as so:

void foo(unsigned int id, uint8_t* data, char len) {
    CANMessage(id, (char*)data, len)
}

But I get "Argument of type std::uint8_t * is incompatible with parameter of type char*

How do I pass it as const char* when function foo, which calls it, accepts uint8_t*?

Please note I can't change types, dta has to stay vector<uint8_t>.


Solution

  • std::uint8_t ιs equal to unsigned char.

    This is different from plain char or signed char, but all of them are 8 bit, therefore casting would techically work.

    It's common that many functions that would otherwise need a "buffer" have a char* in their definition instead of the proper unsigned char*. Therefore, casting would most probably be harmless.

    In the case that the function actually wants characters but not a buffer, then you have a problem because the types are different, and whether you will have an issue or not is undefined.