我用了cv::imencode
编码 cv::Mat
作为image/jpeg
进入 vector<uchar>
现在我想将该 vector 转换为类型 char *
.
vector<uchar> buf;
// print buf to stdout to ensure that data is valid here
for (auto c : buf)
cout << c << endl;
// cast vector to char
char *ch = reinterpret_cast<char*>(buf.data());
// print out value of char pointer
for(int i = 0; ch[i] != '\0'; i++)
printf("log: %c\n", ch[i]);
vector 上的 for 循环取自 this question .
Actor 来自std::vector<T>
至 char *
取自 this question .
现在的问题是在类型转换过程中似乎有一些数据丢失。鉴于 buf
包含有效数据我总是只得到值 ????
从 ch
打印.
知道这里发生了什么吗?
最佳答案
当您使用 vector 时,一切都很好,因为 à vector 是一个具有明确大小的动态数组。所以它可以包含空值。
但接下来,您将使用一个空终止无符号字符数组。所以它在第一个空字符处停止。它甚至在您的代码中是明确的。
for(int i = 0; ch[i] != '\0'; i++)
printf("log: %c\n", ch[i]);
(相关部分是 ch[i] != 0
)
这就是为什么您在第一个空字符之后丢失所有内容的原因。
关于c++ - std::vector<uchar> 到 char* 数据丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30011508/