Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pin an array of byte?

Tags:

I want to pin an array of bytes which is 10 megabytes long so that managed and unmanaged code can work on it.

My scenario is that I have an unmanaged driver which reads some data from the device and writes it to the big array and the managed application just reads that data.

Something like this:

byte[] dataArray = new byte[10*1024*1024]; 

I want to pin dataArray so that GC does not move it.

What happens actually when I just run the application, I get a DataAbortApplication, and after reading on the internet I found out that I should pin the dataArray to avoid this error.

How/what should I do?

like image 326
ShrShr Avatar asked Apr 23 '14 20:04

ShrShr


People also ask

How much can a byte array hold?

MAX_VALUE or about 2 billion regardless of the type of the array.

What are arrays of bytes?

What is a Bytearray? A byte array is simply a collection of bytes. The bytearray() method returns a bytearray object, which is an array of the specified bytes. The bytearray class is a mutable array of numbers ranging from 0 to 256.

What is byte array in C?

byte array in CAn unsigned char can contain a value from 0 to 255, which is the value of a byte. In this example, we are declaring 3 arrays – arr1, arr2, and arr3, arr1 is initialising with decimal elements, arr2 is initialising with octal numbers and arr3 is initialising with hexadecimal numbers.

Is byte array a data type?

The bytearray type is a mutable sequence of integers in the range between 0 and 255. It allows you to work directly with binary data. It can be used to work with low-level data such as that inside of images or arriving directly from the network. Bytearray type inherits methods from both list and str types.


1 Answers

There are 2 ways to do this. The first is to use the fixed statement:

unsafe void UsingFixed() {     var dataArray = new byte[10*1024*1024];     fixed (byte* array = dataArray)     {         // array is pinned until the end of the 'fixed' block     } } 

However, it sounds like you want the array pinned for a longer period of time. You can use GCHandles to accomplish this:

void UsingGCHandles() {     var dataArray = new byte[10*1024*1024];     var handle = GCHandle.Alloc(dataArray, GCHandleType.Pinned);      // retrieve a raw pointer to pass to the native code:     IntPtr ptr = handle.ToIntPtr();      // later, possibly in some other method:     handle.Free(); } 
like image 113
porges Avatar answered Sep 20 '22 04:09

porges