I am writing a library for mixed-languages and so we have to stick to a C interface. I need to call this API function:
void getproperty(const char * key, /* in */
char * value /* out */) {
I need to set value with the contents of an std::string.
std::string stdString = funcReturningString();
// set value to contents of stdString
I've seen lots of answers on possible strategies, but none for this specific use-case and neither were any considered the "best" or "standard." We are using C++11, for what its worth. Some of the answers vaguely recommended copying the contents of the string to a buffer and using that. But how to do it? I would like some more opinions on this conversation so I can finally pick a strategy and stand by it.
Thank you!
UPDATE: Here is the solution I used
I am using uint32_t to keep consistent with the other API functions. bufferSize is a reference because FORTRAN calls everything by reference.
void getproperty(const char * key, /* in */
const uint32_t & bufferSize, /* in */
char * value, /* out */
uint32_t & error /* out */)
{
std::string stdString = funcReturningString();
if (bufferSize < str.size() + 1) {
// Set the error code, set an error message, and return
}
strcpy(value, stdString.c_str());
}
I chose strcpy() to keep everything standard and I chose a bufferSize parameter so that I wouldn't have to worry about some of problems of double indirection mentioned in the comments.