简体   繁体   中英

What is “std::vector<unsigned char> Data = example”?

std::vector<unsigned char> Data = example

I found this on the internet somewhere and I think it writes an array of bytes of unknown size to a given address but I'm not entirely sure. Can anyone explain what this does?

And if this doesn't do what I think it does can someone help me produce a C++ function that takes an address and bytes as arguments and writes them at that address ie:

myfunction(0xaddress, {0x10, 0x11, 0x12}); // something like this

The = operator of a vector will copy the contents of the rvalue (assuming rvalue is of type vector with the same type or a class which implements a casting to a vector from this same type).

No address is being copied here only the contents.

If you want to write an x amount of bytes to an address, you have a number of options.

void myfunction(void* address, size_t count, const unsigned char data[])
{..}

const unsigned char bytes[] = {0x10, 0x11, 0x12};
myfunction (address, 3, bytes);

where the second argument, count, is the length of the array.
Or with a variadic function:

void myfunction(void* address, size_t count, ...)
{..}

myfunction (address, 3, 0x10, 0x11, 0x12);

In all cases, you'll need to give the byte count explicitly though; the compiler can't deduce that from the data.

If you want to use a vector, that's possible, but you'll need to populate the vector first before calling the function, which isn't as efficient.

The only case where you wouldn't need to provide the count yourself is if none of the bytes would have value 0, then you could write

void myfunction(void* address, const char* str)
{..}

myfunction (address, "\x10\x11\x12");

because you could use strlen!

Edit: Also, std::basic_string<unsigned char> would be worth looking into. But here too, it's not trivial to give this a value that contains \\x00 values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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