Poperton
Poperton

Reputation: 2127

How to cast from `std::vector<uint8_t>` to `std::vector<int8_t>`?

I need to fill data into SetByteArrayRegion:

void JNIEnv::SetByteArrayRegion(jbyteArray array, jsize start, jsize len, const jbyte *buf)

where jbyte is simply int8_t. I have a vector of uint8_t. Why I cannot cast it to a vector of int8_t? uint8_t and int8_t have the same size so they could be casted easily.

std::vector<uint8_t> messageResponseVector_ = //...
std::vector<int8_t> messageResponseVector = static_cast<std::vector<int8_t>>(messageResponseVector_);//does not work

What is best to do in this situation? I receive the vector as std::vector<uint8_t>. I could convert easily to std::vector<int8_t> with a for loop but is there an easier way?

Upvotes: 0

Views: 1846

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 595367

You can't cast a vector<uint8_t> to a vector<int8_t>, they are completely separately and unrelated types. But, you can cast the data instead, eg:

std::vector<uint8_t> messageResponseVector_ = //...
jbyte *data = reinterpret_cast<jbyte*>(messageResponseVector_.data());
env->SetByteArrayRegion(array, 0, messageResponseVector_.size(), data);

Though, technically this is undefined behavior, due to strict aliasing rules. The safer option is to simply copy the data into a separate vector<jbyte>, eg:

std::vector<uint8_t> messageResponseVector_ = //...
std::vector<jbyte> messageResponseVector2_(messageResponseVector_.begin(), messageResponseVector_.end());
jbyte *data = messageResponseVector2_.data();
env->SetByteArrayRegion(array, 0, messageResponseVector2_.size(), data);

Otherwise, see if you can change your code to receive messageResponseVector_ as a vector<int8_t> (if not vector<jbyte>) to begin with:

std::vector<int8_t> messageResponseVector_ = //...
jbyte *data = reinterpret_cast<jbyte*>(messageResponseVector_.data());
env->SetByteArrayRegion(array, 0, messageResponseVector2_.size(), data);

Upvotes: 1

user
user

Reputation: 944

#include <vector>
#include <algorithm>
int foo() {
    std::vector<uint8_t> messageResponseVector_;
    std::vector<int8_t> messageResponseVector2(messageResponseVector_.begin(), messageResponseVector_.end());
}

Upvotes: 1

Related Questions