I'm working in a C++ unmanaged project.
I need to know how can I take a string like this "some data to encrypt" and get a byte array which I'm gonna use as the source for Encrypt.
In C# I do
for (int i = 0; i < text.Length; i++) buffer[i] = (byte)text[i];
What I need to know is how to do the same but using unmanaged C++.
If you just need read-only access, then
c_str() will do it:
char const *c = myString.c_str();
If you need read/write access, then you can copy the string into a vector. vectors manage dynamic memory for you. You don't have to mess with allocation/deallocation then:
std::vector<char> bytes(myString.begin(), myString.end()); bytes.push_back('\0'); char *c = &bytes;
unsigned char buffer[mystring.length()]; memcpy(buffer, mystring.data(), mystring.length());
STL fanboys would encourage you to use std::copy instead:
std::copy(mystring.begin(), mystring.end(), buffer);
but there really isn't much of an upside to this. If you need null termination use
std::string::c_str() and the various string duplication techniques others have provided, but I'd generally avoid that and just query for the
length. Particularly with cryptography you just know somebody is going to try to break it by shoving nulls in to it, and using
std::string::data() discourages you from lazily making assumptions about the underlying bits in the string.