C interface provides a pointer and a length... wrap without copying?

Nicholas Wilson via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Mar 11 15:43:54 PST 2017


On Saturday, 11 March 2017 at 22:39:02 UTC, cy wrote:
> So a lovely C library does its own opaque allocation, and 
> provides access to the malloc'd memory, and that memory's 
> length. Instead of copying the results into garbage collected 
> memory (which would probably be smart) I was thinking about 
> creating a structure like:
>
> struct WrappedString {
>   byte* ptr;
>   size_t length;
> }
>
> And then implementing opIndex for it, and opEquals for all the 
> different string types, and conversions to those types, and 
> then it occurred to me that this sounds like a lot of work. Has 
> anybody done this already? Made a pointer/length pair, that 
> acts like a string?

A string *is* a pointer length pair, an immutable(char)[]. Your 
`WrappedString` is effectively a byte[].

All you need to do is:

ubyte[] arr; // or byte/char whatever is the pointed to type 
returned by giveMeTheMemory
arr = giveMeTheMemory()[0 .. getMeTheLength()];

No need to reimplement anything.


More information about the Digitalmars-d-learn mailing list