本文介绍了数组<字节>^ 和字节* 之间的区别是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

并且是否可以将数组转换为

字节>^ 到一个字节*?

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^ 是托管堆中对象的句柄,byte* 是指向非托管字节的指针.您不能在它们之间进行转换,但可以修复托管数组并获取指向其中元素的指针.

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 回应第一条评论:

这是取自 此页面的代码示例 在 msdn 上

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

您最感兴趣的是 void Load() 方法.在这里,他们固定数组,并获取指向其中第一个元素的指针...

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

这篇关于数组<字节>^ 和字节* 之间的区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-19 04:04