简体   繁体   English

复制 std::vector<unsigned char> 使用 memcpy 取消 * 缓冲区

[英]copying std::vector<unsigned char> to void * buffer using memcpy

I have a custom function which copying values to the buffer我有一个将值复制到缓冲区的自定义函数

void foo(void *buffer, std::initializer_list<unsigned char> l) {
   memcpy(buffer, l.begin(), l.size());
}

Initializer list argument takes hexadecimal value as paramater.初始化列表参数以十六进制值作为参数。 However I want to change it to string representation like instead of passing parameter as {0x01, 0x02, 0x04}, I would like to pass it as "0x01 0x02 0x04".但是,我想将其更改为字符串表示形式,而不是将参数作为 {0x01, 0x02, 0x04} 传递,而是将其作为“0x01 0x02 0x04”传递。

I changed std::initializer_list<unsigned char> to std::vector.我将std::initializer_list<unsigned char>更改为 std::vector。 But I got invalid casting error from vector to void * .但是我得到了从vectorvoid *无效转换错误。

void foo(void *buffer, std::vector<unsigned char> l) {
   memcpy(buffer, reinterpret_cast<void *>(l.begin()), l.size());
}

std::vector::begin returns an iterator not a pointer to the first element. std::vector::begin返回一个迭代器而不是指向第一个元素的指针。 Try...尝试...

void foo(void *buffer, std::vector<unsigned char> l)
{
    memcpy(buffer, l.data(), l.size());
}

Better still, if the vector is large then you might want to consider passing by const reference rather than by value...更好的是,如果向量很大,那么您可能需要考虑通过 const 引用而不是通过值传递......

void foo(void *buffer, const std::vector<unsigned char> &l)
{
    memcpy(buffer, l.data(), l.size());
}

Although iterators returned from .begin() or .end() might work like pointers,尽管从 .begin() 或 .end() 返回的迭代器可能像指针一样工作,
but that does not guarantee that they are really alias of real pointers.但这并不能保证它们真的是真实指针的别名。
Think of iterators from std::map for example.例如,想想std::map的迭代器。
They should contain more information rather than just a pointer since they iterate through binary tree.它们应该包含更多信息而不仅仅是一个指针,因为它们遍历二叉树。

It makes sense to think of iterator from continuous container as pointer,将连续容器中的迭代器视为指针是有意义的,
maybe they really are, but remember the C++ standard does not guarantee it.也许它们确实如此,但请记住 C++ 标准并不能保证这一点。

Anyways, here's my solution.无论如何,这是我的解决方案。

void foo(void *buffer, std::vector<unsigned char> l) {
   memcpy(buffer, &*l.begin(), l.size());
}

Looks weird but does the job correctly.看起来很奇怪,但可以正确完成工作。
The other answer's solution looks more elegant tho :)另一个答案的解决方案看起来更优雅 :)

If using memcpy isn't an absolute requirement, there's a higher-level approach:如果使用memcpy不是绝对要求,则有一种更高级别的方法:

std::uninitialized_copy(l.begin(), l.end(), (unsigned char*)buffer);

But I'd make it more general:但我会让它更一般:

template <class Iter>
void foo(void *buffer, Iter first, Iter last) {
    typedef typename std::iterator_traits<Iter>::value_type *ptr;
    std::uninitialized_copy(first, last, static_cast<ptr>(buffer));
}

This one works with any range and any type.这个适用于任何范围和任何类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM