byte* and int length -> byte[]
Vijay Nayar
madric at gmail.com
Mon Aug 15 12:19:37 PDT 2011
On Mon, 15 Aug 2011 17:16:54 +0000, mimocrocodil wrote:
> I obtain immutable(byte)* and int where contained length of bytes block
> from C library.
>
> Can I convert this into byte[] without explict copying etc.
>
> Something like:
>
> byte* p; // bytes
> int size; // size of bytes block
>
> byte[] b;
> b.length = size;
> b.ptr = p;
>
> // now b contains bytes from library
The question presented here really has two parts:
1) Can you declare a new symbol without duplicating the original data?
2) Can a mutable symbol reference an immutable pointer?
The short answer to (1) is yes, if you do not need mutability.
The short answer to (2) is no.
The following small program demonstrates this:
import std.stdio;
void main() {
// Reference data to play with.
immutable(byte)[] data = [0, 1, 2, 3, 4, 5, 6, 7];
// These two lines simulate having an immutable byte pointer.
immutable(byte)* ptr = data.ptr;
auto ptr_len = data.length;
// Making an immutable copy is easy, 'auto' works here too.
immutable(byte)[] immutableCopy = ptr[2 .. 6];
// Error! Cannot implicitly convert to immutable.
//byte[] badMutableCopy = ptr[2 .. 6];
byte[] goodMutableCopy = immutableCopy.dup;
// Make a simple edit to our mutable copy.
foreach (ref b; goodMutableCopy) {
b++;
}
// Output is: 2,3 3,4 4,5 5,6
for (auto i=0; i < immutableCopy.length; i++) {
writeln(immutableCopy[i], ',', goodMutableCopy[i]);
}
}
More information about the Digitalmars-d-learn
mailing list