开发者

Whats the diffrence between an array<Byte>^ and a byte*?

And is it possible to cast the array< Byte>^ to an byte*?

how would the below code need to changed to return a byte*?

array<Byte>^ StrToByteArray(System::String^ unicodeString)
{
    UTF8Encoding^ utf8 = gcnew UTF8Encoding;
    array<Byte>开发者_运维技巧^ encodedBytes = utf8->GetBytes( unicodeString );
    return encodedBytes;
}


array^ is a handle to an object in the managed heap, byte* is a pointer to an unmanaged byte. You cannot cast between them, but it is possible to fix the managed array and obtain a pointer to the elements within it.

EDIT in response to first comment:

Here's a code sample taken from this page on msdn

The bit you are most interested in is the void Load() method. Here they are pinning the array, and taking a pointer to the first element in it...

// pin_ptr_1.cpp
// compile with: /clr 
using namespace System;
#define SIZE 10

#pragma unmanaged
// native function that initializes an array
void native_function(byte* p) {
    for(byte i = 0 ; i < 10 ; i++)
        p[i] = i;
}
#pragma managed

public ref class A {
private:
    array<byte>^ arr;   // CLR integer array

public:
    A() {
        arr = gcnew array<byte>(SIZE);
    }

    void load() {
        pin_ptr<byte> p = &arr[0];   // pin pointer to first element in arr
        byte* np = p;   // pointer to the first element in arr
        native_function(np);   // pass pointer to native function
    }

    int sum() {
        int total = 0;
        for (int i = 0 ; i < SIZE ; i++)
            total += arr[i];
        return total;
    }
};

int main() {
    A^ a = gcnew A;
    a->load();   // initialize managed array using the native function
    Console::WriteLine(a->sum());
}


No, you cannot cast it, but array has a method that returns the raw array called "data()"

EDIT: nvm, thought you were talking about the stl class array.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜