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

China☆狼群 提交于 2019-12-01 12:33:15

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!