Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Convert unsafe byte* to byte[]

Tags:

c#

pinvoke

I have an unsafe byte* pointing to a native byte array of known length. How can I convert it to byte[]?

An unsafe sbyte* pointing to a zero-terminated native string can be converted to a C# string easily, because there is a conversion constructor for this purpose, but I can't find a simple way to convert byte* to byte[].

like image 324
kol Avatar asked Jul 10 '13 11:07

kol


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.

What is C full form?

Full form of C is “COMPILE”. One thing which was missing in C language was further added to C++ that is 'the concept of CLASSES'.


2 Answers

If ptr is your unsafe pointer, and the array has length len, you can use Marshal.Copy like this:

byte[] arr = new byte[len];
Marshal.Copy((IntPtr)ptr, arr, 0, len);

But I do wonder how you came by an unsafe pointer to native memory. Do you really need unsafe here, or can you solve the problem by using IntPtr instead of an unsafe pointer? And if so then there's probably no need for unsafe code at all.

like image 130
David Heffernan Avatar answered Oct 07 '22 00:10

David Heffernan


The Marshal class could help you.

byte[] bytes = new byte[length];
for(int i = 0; i < length; ++i)
  bytes[i] = Marshal.ReadByte(yourPtr, i);

I think you might use Marshal.Copy too.

like image 26
dotixx Avatar answered Oct 06 '22 23:10

dotixx