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 &amp; bufferSize, /* in  */                  char * value,                /* out */                  uint32_t &amp; error             /* out */)  {   std::string stdString = funcReturningString();    if (bufferSize &lt; 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.
7285
How can I convert an std::string to a char* or a const char*?
44888
I'm reading The C++ Programming Language and in it Stroustrup states that the int value of a char can range from 0 to 255 or -127 to 127, depending on implementation. Is this correct? It seems like it should be from -128 to 127.  If not, why are their only 255 possible values in the second implementation possibility, not 256.
14231
What would be the best way to fill a C# struct from a byte[] array where the data was from a C/C++ struct?  The C struct would look something like this (my C is very rusty):  typedef OldStuff {     CHAR Name[8];     UInt32 User;     CHAR Location[8];     UInt32 TimeStamp;     UInt32 Sequence;     CHAR Tracking[16];     CHAR Filler[12]; }   And would fill something like this:  [StructLayout(LayoutKind.Explicit, Size = 56, Pack = 1)] public struct NewStuff {     [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]     [FieldOffset(0)]     public string Name;      [MarshalAs(UnmanagedType.U4)]     [FieldOffset(8)]     public uint User;      [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]     [FieldOffset(12)]     public string Location;      [MarshalAs(UnmanagedType.U4)]     [FieldOffset(20)]     public uint TimeStamp;      [MarshalAs(UnmanagedType.U4)]     [FieldOffset(24)]     public uint Sequence;      [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]     [FieldOffset(28)]     public string Tracking; }   What is best way to copy OldStuff to NewStuff, if OldStuff was passed as byte[] array?  I'm currently doing something like the following, but it feels kind of clunky.  GCHandle handle; NewStuff MyStuff;  int BufferSize = Marshal.SizeOf(typeof(NewStuff)); byte[] buff = new byte[BufferSize];  Array.Copy(SomeByteArray, 0, buff, 0, BufferSize);  handle = GCHandle.Alloc(buff, GCHandleType.Pinned);  MyStuff = (NewStuff)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(NewStuff));  handle.Free();   Is there better way to accomplish this?    Would using the BinaryReader class offer any performance gains over pinning the memory and using Marshal.PtrStructure?
46146
I often use the execv() function in C++, but if some of the arguments are in C++ strings, it annoys me that I cannot do this: const char *args[4];  args[0] = &quot;/usr/bin/whatever&quot;; args[1] = filename.c_str(); args[2] = someparameter.c_str(); args[3] = 0;  execv(args[0], args);  This doesn't compile because execv() takes char *const argv[] which is not compatible with const char *, so I have to copy my std::strings to character arrays using strdup(), which is a pain. Does anyone know the reason for this?
13479
Note that this function does not have a "{" and "}" body.  Just a try/catch block:  void func( void ) try {     ... } catch(...) {     ... }   Is this intentionally part of C++, or is this a g++ extension?  Is there any purpose to this other than bypass 1 level of {}?  I'd never heard of this until I ran into
25119
Is it possible to convert UTF8 string in a std::string to std::wstring and vice versa in a platform independent manner? In a Windows application I would use MultiByteToWideChar and WideCharToMultiByte. However, the code is compiled for multiple OSes and I'm limited to standard C++ library.
28304
If I have a unit that is filled with constants like...  unit AConsts; interface const    Const1 : WideString = 'Const1';    Const2 : WideString = 'Const2';    Const3 : WideString = 'Const3';    Const4 = 100;    Const5 = 100; implementation end.   and I want to use this unit from another unit, is there any difference between...  unit AUnit; interface uses    AConsts; Implementation end.   and   unit AUnit; interface implementation uses   AConsts; end.   ?  The question is not about scope, avoiding circular references etc. It is about differences in the compiled application.  If UnitA, UnitB and UnitC all use AConsts, would there be a difference in the compiled application (assuming no name clashes between the constants in the AConsts unit and other code) between App1 where these UnitA, UnitB and UnitC all have AConsts in the interface section and App2 where UnitA, UnitB and UnitC all have AConsts in the implementation section.
122420
I get a transmission over the network that's an array of chars/bytes. It contains a header and some data. I'd like to map the header onto a struct. Here's an example:  #pragma pack(1)  struct Header {     unsigned short bodyLength;     int msgID;     unsigned short someOtherValue;     unsigned short protocolVersion; };  int main() {     boost::array&lt;char, 128&gt; msgBuffer;     Header header;      for(int x = 0; x &lt; sizeof(Header); x++)         msgBuffer[x] = 0x01; // assign some values      memcpy(&amp;header, msgBuffer.data(), sizeof(Header));      system("PAUSE");          return 0; }   Will this always work assuming the structure never contains any variable length fields? Is there a platform independent / idiomatic way of doing this?  Note:  I have seen quite a few libraries on the internet that let you serialize/deserialize, but I get the impression that they can only deserialize something if it has ben previously serialized with the same library. Well, I have no control over the format of the transmission. I'm definitely going to get a byte/char array where all the values just follow upon each other.
49609
I have a bunch of enum types in some library header files that I'm using, and I want to have a way of converting enum values to user strings - and vice-versa.   RTTI won't do it for me, because the 'user strings' need to be a bit more readable than the enumerations.  A brute force solution would be a bunch of functions like this, but I feel that's a bit too C-like.  enum MyEnum {VAL1, VAL2,VAL3};  String getStringFromEnum(MyEnum e) {   switch e   {   case VAL1: return "Value 1";   case VAL2: return "Value 2";   case VAL1: return "Value 3";   default: throw Exception("Bad MyEnum");   } }   I have a gut feeling that there's an elegant solution using templates, but I can't quite get my head round it yet.  UPDATE: Thanks for suggestions - I should have made clear that the enums are defined in a third-party library header, so I don't want to have to change the definition of them.  My gut feeling now is to avoid templates and do something like this:  char * MyGetValue(int v, char *tmp); // implementation is trivial  #define ENUM_MAP(type, strings) char * getStringValue(const type &amp;T) \  { \  return MyGetValue((int)T, strings); \  }  ; enum eee {AA,BB,CC}; - exists in library header file  ; enum fff {DD,GG,HH};   ENUM_MAP(eee,"AA|BB|CC") ENUM_MAP(fff,"DD|GG|HH")  // To use...      eee e;     fff f;     std::cout&lt;&lt; getStringValue(e);     std::cout&lt;&lt; getStringValue(f);
7366
How do I read a file into a std::string, i.e., read the whole file at once?  Text or binary mode should be specified by the caller. The solution should be standard-compliant, portable and efficient. It should not needlessly copy the string's data, and it should avoid reallocations of memory while reading the string.  One way to do this would be to stat the filesize, resize the std::string and fread() into the std::string's const_cast&lt;char*&gt;()'ed data(). This requires the std::string's data to be contiguous which is not required by the standard, but it appears to be the case for all known implementations. What is worse, if the file is read in text mode, the std::string's size may not equal the file's size.  A fully correct, standard-compliant and portable solutions could be constructed using std::ifstream's rdbuf() into a std::ostringstream and from there into a std::string. However, this could copy the string data and/or needlessly reallocate memory.    Are all relevant standard library implementations smart enough to avoid all unnecessary overhead?  Is there another way to do it?  Did I miss some hidden Boost function that already provides the desired functionality?     void slurp(std::string&amp; data, bool is_binary)
93954
I had an article, but I lost it.  It showed and described a couple of C/C++ tricks that people should be careful. One of them interested me but now that I am trying to replicate it I'm not being able to put it to compile.  The concept was that it is possible to change by accident the value of a const in C/C++  It was something like this:  const int a = 3;          // I promise I won't change a const int *ptr_to_a = &amp;a; // I still promise I won't change a int *ptr; ptr = ptr_to_a;  (*ptr) = 5;               // I'm a liar; a is now 5   I wanted to show this to a friend but now I'm missing a step.  Does anyone know what's missing for it to start compiling and working?  ATM I'm getting invalid conversion from 'const int*' to 'int*' but when I read the article I tried and it worked great.
48897
I have a C++ library that provides various classes for managing data.  I have the source code for the library.  I want to extend the C++ API to support C function calls so that the library can be used with C code and C++ code at the same time.  I'm using GNU tool chain (gcc, glibc, etc), so language and architecture support are not an issue.  Are there any reasons why this is technically not possible?  Are there any gotcha's that I need to watch out for?  Are there resources, example code and/or documentation available regarding this?    Some other things that I have found out:   Use the following to wrap your C++ headers that need to be used by C code.     #ifdef __cplusplus extern "C" {   #endif   //   // Code goes here ...   //   #ifdef __cplusplus   } // extern "C"   #endif    Keep "real" C++ interfaces in separate header files that are not included by C.  Think  here.  Using #ifndef __cplusplus #error stuff helps here to detect any craziness. Careful of C++ identifiers as names in C code Enums varying in size between C and C++ compilers.  Probably not an issue if you're using GNU tool chain, but still, be careful. For structs follow the following form so that C does not get confused.  typedef struct X { ... } X  Then use pointers for passing around C++ objects, they just have to be declared in C as struct X where X is the C++ object.   All of this is courtesy of a friend who's a wizard at C++.
30179
In C the following horror is valid:  myFunc() {   return 42;  // return type defaults to int. }   But, what about in C++? I can't find a reference to it either way...  My compiler (Codegear C++Builder 2007) currently accepts it without warning, but I've had comments that this is an error in C++.
100259
Is std::string size() a O(1) operation?  The implementation of STL I'm using is the one built into VC++
63970
Possible Duplicate:          I want to write a function that reverses the given string passed into it. But, I can not. If I supply the doReverse function (see code below) with a character array, my code works well.  I can't figure out why this does not work. I am able to access str[0] in doReverse, but I can't change any value of the array by using a char pointer. Any ideas?  void doReverse(char *str) {     str[0] = 'b'; }  void main(void) {     char *str = "abc";     doReverse(str);     puts(str); }   Update:  I know how to do write a reverse function by passing a character array to it:  void reverse1(char p[]) {     int i, temp, y;      for (i = 0, y = strlen(p); i &lt; y; ++i, --y) {         temp = p[y-1];         p[y-1] = p[i];         p[i] = temp;     } }   But, I want to write another version that gets a char pointer as a parameter.
40546
In C/C++, what an unsigned char is used for? How is it different from a regular char?
50510
Whilst refactoring some code I came across some getter methods that returns a std::string.  Something like this for example:  class foo { private:     std::string name_; public:     std::string name()     {         return name_;     } };   Surely the getter would be better returning a const std::string&amp;?  The current method is returning a copy which isn't as efficient.  Would returning a const reference instead cause any problems?