martin
martin

Reputation:

Binary data in .NET? (C++/CLI)

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?

Upvotes: 4

Views: 4012

Answers (3)

Rasmus Faber
Rasmus Faber

Reputation: 49677

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);

Upvotes: 3

aku
aku

Reputation: 124014

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.

Upvotes: 2

Gant
Gant

Reputation: 29889

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.

Upvotes: 1

Related Questions