4

What's the prefered way to store binary data in .NET?

I've tried this:

byte data __gc [] = __gc new byte [100];

And got this error:

error C2726: '__gc new' may only be used to create an object with managed type

Is there a way to have managed array of bytes?

3 Answers 3

3

Are you using Managed C++ or C++/CLI? (I can see that Jon Skeet edited the question to add C++/CLI to the title, but to me it looks like you are actually using Managed C++).

But anyway:

In Managed C++ you would do it like this:

Byte data __gc [] = new Byte __gc [100];

In C++/CLI it looks like this:

cli::array<unsigned char>^ data = gcnew cli::array<unsigned char>(100);
Sign up to request clarification or add additional context in comments.

Comments

2

CodeProject: Arrays in C++/CLI

As far as I know '__gc new' syntax is deprecated, try following:

cli::array<byte>^ data = gcnew cli::array<byte>(100);

I noted that you're having problems with cli namespace. Read about this namespace on MSDN to resolve your issues.

Comments

1

I don't know the preferred way of doing this. But if you only want it compiled, the following are working code from my C++/CLI CLRConsole project from my machine.

#include "stdafx.h"

using namespace System;

int main(array<System::String ^> ^args)
{
    cli::array<System::Byte^>^ a = 
        gcnew cli::array<System::Byte^>(101);

    a[1] = (unsigned char)124;

    cli::array<unsigned char>^ b = 
        gcnew cli::array<unsigned char>(102);

    b[1] = (unsigned char)211;

    Console::WriteLine(a->Length);
    Console::WriteLine(b->Length);

    Console::WriteLine(a[1] + " : " + b[1]);
    return 0;
}

Output:

101
102
124 : 211

a is managed array of managed byte. And b is managed array of unsigned char. C++ seems not to have byte data type built in.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.