简体   繁体   中英

How to pass std::string to const unsigned char ** in C++

How can I pass std::string to unsigned char **?

Example:

/* Func declaration */
void get_string(const unsigned char **str, int *len) {

/* Caller func */
std::string str;
int len = 0;
get_string((const unsigned char **)str.c_str(), &len)      // Can we do this?

You need to read the documentation of get_string and understand what the semantics are of the argument it is expecting.

I'm going to assume for now that the arguments are both output parameters and it outputs a view onto a string that alraedy exists.

std::string manages a string, it can't act just as a view. So you would need to create a new string that is a copy of the one being viewed. The code could be:

unsigned char const *s;
int len;
get_string(&s, &len);
std::string str( (char*)s, len );

If your compiler is up to date with the latest language standard (C++17) then you can use a view:

std::string_view str( (char*)s, len );

assuming of course that the view is sufficient for whatever you intend to do with it later.

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