Closed Thread
Results 1 to 1 of 1

Thread: Convert between managed and unmanaged

  1. #1
    Crane's Avatar
    Crane is offline Programming Expert
    Join Date
    Nov 2005
    Posts
    398
    Rep Power
    25

    Post Convert between managed and unmanaged

    I found these browsing around on the internet (For Studio 2006):

    Unmanaged to Managed:
    ------------------------------------
    char* su;
    String^ sm = gcnew String(su);

    wchar_t* su;
    String^ sm = gcnew String(su);

    std::string su;
    String^ sm = gcnew String(su.c_str());

    std::wstring su;
    String^ sm = gcnew String(su.c_str());

    Managed to Unmanaged:
    ------------------------------------
    Wide string version:
    String^ sm = "Hello";
    pin_ptr<wchar_t> pu = PtrToStringChars(sm);

    // PtrToStringChars is an inline function in vcclr.h, and it returns
    // a raw pointer to the internal representation of the String.
    // After pinning "p", it can be passed to unmanaged code:
    wchar_t* su = pu;
    // when "pu" goes out of scope, "su" becomes invalid!

    Ansi (8-bit) version:
    ScopedHGlobal s_handle(Marshal::StringToHGlobalAnsi(sm));
    char* su = s_handle.c_str();
    // when "s_handle" goes out of scope, "su" becomes invalid!
    Where ScopedHGlobal is a helper class written by myself:
    using namespace System::Runtime::InteropServices;
    public ref class ScopedHGlobal
    {
    public:
    ScopedHGlobal(IntPtr p) : ptr(p) { }
    ~ScopedHGlobal() { Marshal::FreeHGlobal(ptr); }
    char* c_str() {
    return reinterpret_cast<char*>(ptr.ToPointer());
    }
    private:
    System::IntPtr ptr;
    };
    Last edited by Crane; 11-03-2005 at 01:48 PM.

  2. CODECALL Circuit advertisement
    Join Date
    Always
    Posts
    Many

     
Closed Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. [Linux] Convert and then convert again and ...
    By sakishrist in forum C and C++
    Replies: 2
    Last Post: 06-19-2011, 12:19 PM
  2. Help with unmanaged Code
    By Saniza007 in forum Visual Basic Programming
    Replies: 1
    Last Post: 11-16-2010, 11:01 PM
  3. Replies: 0
    Last Post: 08-28-2009, 01:22 PM
  4. Callbacks in c# from unmanaged C DLL
    By paul_chapman in forum C# Programming
    Replies: 0
    Last Post: 01-18-2007, 08:26 AM
  5. Managed C++ vs C# IDE
    By Crane in forum Managed C++
    Replies: 2
    Last Post: 09-05-2006, 09:16 AM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts