array<Byte> to standard char[] and back
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Thread: array<Byte> to standard char[] and back

  1. #1
    Join Date
    Jan 2006
    Posts
    74

    array<Byte> to standard char[] and back

    What is the best way to convert a array<Byte> to a normal char[] and vise versa? At the moment I am interating through every element in them and copying each part over one at a time but their has to be a better way.

  2. #2
    Join Date
    Aug 2005
    Location
    Netherlands, The
    Posts
    2,184

    Re: array<Byte> to standard char[] and back

    a char and a byte are the same.

  3. #3
    Join Date
    Nov 2006
    Posts
    2

    Re: array<Byte> to standard char[] and back

    Here's an example. Use the InteropServices::Marshal class to 'marshal' the array from unmanaged to managed and use 'pin_ptr' to 'pin' the pointer (because managed memory is moveable) to gain access to the managed array...


    // CLR_Console.cpp : main project file.

    #include "stdafx.h"
    #include <string>

    using namespace System;
    using namespace System::Runtime::InteropServices;

    int main(array<System::String ^> ^args)
    {
    std::string s = "Hello world.";

    // unmanaged to managed...
    IntPtr ptr((void*)s.data());
    int len = s.length();
    array<Byte>^ bytes = gcnew array<Byte>(len);
    Marshal::Copy(ptr, bytes, 0, len);

    // managed to unmanaged...
    pin_ptr<Byte> p = &bytes[0];

    std::string new_string((const char*)p);

    return 0;
    }

  4. #4
    Join Date
    Apr 2004
    Location
    England, Europe
    Posts
    2,492

    Re: array<Byte> to standard char[] and back

    Quote Originally Posted by Mitsukai
    a char and a byte are the same.
    In .net they are different sizes.

    Quote Originally Posted by practisevoodoo
    What is the best way to convert a array<Byte> to a normal char[] and vise versa? At the moment I am interating through every element in them and copying each part over one at a time but their has to be a better way.
    I assume you mean a byte array to a System::Char array.

    When I need to do this, I create a MemoryStream and a BinaryWriter / BinaryReader.

    Code:
    IO::MemoryStream stream = gcnew IO::MemoryStream(destinationArray, true);
    IO::BinaryWriter writer = gcnew IO::BinaryWriter(stream);
    Last edited by Zaccheus; November 16th, 2006 at 07:19 AM.
    My hobby projects:
    www.rclsoftware.org.uk

Posting Permissions

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


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center