converting D's string to use with C API with unicode

Jack jckj33 at gmail.com
Sun Dec 6 02:07:10 UTC 2020


On Saturday, 5 December 2020 at 23:31:31 UTC, tsbockman wrote:
> On Saturday, 5 December 2020 at 21:55:13 UTC, Jack wrote:
>> my code now look like this, still there's a memory corrupt. 
>> Could anyone help point out where is it?
>>
>> ...
>>
>>> foreach(i; 0..output.length) {
>>>     wstring ws;
>>>     transcode(output[i], ws);
>>>     auto s = malloc(ws.length + 1);
>>>     if(!s) {
>>>         onOutOfMemoryError();
>>>     }
>>>     memcpy(s, ws.ptr, ws.length);
>
> `ws.length` is the length in `wchar`s, but `memcpy` expects the 
> size in bytes. (This is because it takes `void*` pointers as 
> inputs, and so does not know the element type or its size.)

How do I get this size in bytes from wstring?

> Also, I think you need to manually zero-terminate `s`. You 
> allocate space to do so, but don't actually use it. (I believe 
> that transcode will only zero-terminate the destination if the 
> source argument is already zero-terminated.)
>
>>>     r.output[i] = cast(wchar*)s;
>>> }

I'll fix




More information about the Digitalmars-d-learn mailing list