Cannot convert from byte* to byte[]

  • Thread starter valentin tihomirov
  • Start date
V

valentin tihomirov

The conversion shold be trivial -- no conversion copy. In essense, both
types are pointers to byte array. The difference is purely semantical.

unsafe {
byte b = 1;
byte[] data = &b;
}


Actually, I considered establishing data reference in a structure:

[StructLayout(LayoutKind.Sequential)]
struct Struct {
public UInt32 count;
public byte[] pData;
}
 
A

Alun Harford

valentin said:
The conversion shold be trivial -- no conversion copy. In essense, both
types are pointers to byte array. The difference is purely semantical.

unsafe {
byte b = 1;
byte[] data = &b;
}

The difference isn't purely semantic in C#. Unlike C, C# arrays have
additional information such as length.
To get a byte[] from a byte*, use

Marshal.Copy(new IntPtr(pointerToConvert), byteArrayName, 0, arraySize);

Alun Harford
 
V

valentin tihomirov

The difference isn't purely semantic in C#. Unlike C, C# arrays have
additional information such as length.

There should be a way to define a plain array then. Like in Delphi, which
exposes dynamic arrays with variable length and system managed lifetime
while retaining the basic ones.

I have succeeded declaring the array as IntPtr with explicit casting array
to IntPtr and, later, by declaring the array as byte*. The problem of C#, as
I noob see it, is that you should have different declarations of structures
and P/Invokable functions for safe and unsafe code. IntPtr is opaque but is
allowed in safe context; static arrays is convetient for unsafe but
precludes using structure in safe mode.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top