D string to C struct fixed-size array

bdh ben.h at posteo.net
Tue Jan 5 03:34:09 UTC 2021


On Monday, 4 January 2021 at 16:35:23 UTC, Jack wrote:
> Do you mean fill .filename member from a D string? something 
> like this?
>
> [...]
>
>     // since .filename isn't a pointer but an array, I think
>     // you have to use memcpy() here. = operator wouldn't work 
> properly.
>     memcpy(&i.filename[0], &cs[0], strlen(cs)+1);

I'm pretty sure I tried using = but it resulted in a type error 
(or array length mismatch).
Also tried memcpy which compiled, though due to the incorrect 
struct definition it appeared to not work.

>     // casting away arrayness to make it a pointer (that a C's 
> array is after all)
>     printf("str = [%s]\n", &i.filename[0]);

I'll keep this and ...

> note that even if .filename was a pointer, in order to the C 
> converted stirng don't turn into garbage in a GC cycle, you 
> would have to either keep reference to dstr around or malloc() 
> and memcpy()

... this in mind, thanks.



More information about the Digitalmars-d-learn mailing list