Why is Marshal::StringToHGlobalAnsi argument not const?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Kenneth Porter

    #1

    Why is Marshal::StringToHGlobalAnsi argument not const?

    I try to be const correct everywhere and found that I can't pass a const
    String to this API. Is it going to change the value? Or is the signature
    not the best it could be?

    I want to write this:

    // based on http://msdn.microsoft.com/en-us/magazine/bb985936.aspx

    std::string MarshalString (const System::String^ s)
    {
    using namespace System::Runtime ::InteropServic es;
    const char* chars =
    (const char*)(Marshal: :StringToHGloba lAnsi
    (s)).ToPointer( );
    os = chars;
    Marshal::FreeHG lobal(IntPtr((v oid*)chars));
    return os;
    }

    Should I copy the argument and convert the copy?
  • Kenneth Porter

    #2
    Re: Why is Marshal::String ToHGlobalAnsi argument not const?

    Kenneth Porter <shiva.blacklis t@sewingwitch.c omwrote in
    news:Xns9A92C01 0EA61Cshivawell com@207.46.248. 16:
    I try to be const correct everywhere and found that I can't pass a const
    String to this API. Is it going to change the value? Or is the signature
    not the best it could be?
    I've discovered the answer to my question. The CLR threw const-correctness
    on the scrap heap to be compatible with VB's lack of const, and that
    decision infected C# and C++/CLI:

    http://blogs.msdn.com/oldnewthing/ar...27/121049.aspx

    So I guess I'll be copying my const Strings to non-const Strings before
    passing them to system libraries.

    Comment

    • Ben Voigt [C++ MVP]

      #3
      Re: Why is Marshal::String ToHGlobalAnsi argument not const?


      "Kenneth Porter" <shiva.blacklis t@sewingwitch.c omwrote in message
      news:Xns9A92C42 7F1EFBshivawell com@207.46.248. 16...
      Kenneth Porter <shiva.blacklis t@sewingwitch.c omwrote in
      news:Xns9A92C01 0EA61Cshivawell com@207.46.248. 16:
      >
      >I try to be const correct everywhere and found that I can't pass a const
      >String to this API. Is it going to change the value? Or is the signature
      >not the best it could be?
      >
      I've discovered the answer to my question. The CLR threw const-correctness
      on the scrap heap to be compatible with VB's lack of const, and that
      decision infected C# and C++/CLI:
      Yup, and you can't do *anything* with a const managed type, because there
      aren't any const member functions, so even reading properties isn't
      possible. There's no syntax for defining const member functions in your own
      types either, although it would have been easy for the C++ compiler to
      implement this using attributes.
      >
      http://blogs.msdn.com/oldnewthing/ar...27/121049.aspx
      >
      So I guess I'll be copying my const Strings to non-const Strings before
      passing them to system libraries.

      Comment

      Working...