interfacing with C: strings and byte vectors

ag0aep6g via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jun 11 06:32:07 PDT 2016


On 06/11/2016 01:59 PM, yawniek wrote:
> i forgot to add a few important points:
> - the strings in vec_t are not c strings
> - vec_t might contain other data than strings
>
> the original ctor i pasted actually doesn't even work, temporarly i
> solved it like
>
>      this(string s) {
>          char[] si = cast(char[]) s; //i'm scared

Rightfully so. Casting away immutable shouldn't be done lightly.

>          base = si.ptr;
>          len = si.length;
>      }
> is there a better solution than to fearlessly cast away immutability?
> i guess i could just make a second vec_t that has immutable base and length
> that can be used in D to stay clean, would that be worth anything?

Sure. You wouldn't have to do the risky cast then.

> now what i still don't have a proper idea for is how can i create
> wrappers for the
> methods accepting vec_t in a clean way.
> for the vec_t that are allocated in D-land we can state that the C libs
> will not modify the data.
> there is a lot of functions that accept vec_t.
> is there no way to have  strings auto cast to vec_t ?

I don't think so, no. You can make a new type and use alias this to have 
it convert implicitly to vec_t, but you can't enable that for string.

There is no feature to implicitly convert *from* another type, only *to* 
another type.

> another way i see is a UDA that generates the wrapper function(s).
> other ideas?

Generating the wrappers seems ok to me.

Regarding a UDA: I haven't really used them, but you'd still have to 
iterate over all functions that have the attribute, right? At that 
point, the UDA might be pointless. Can also iterate over everything and 
check if there's a vec_t parameter.


More information about the Digitalmars-d-learn mailing list