Allocating a wstring on the stack (no GC)?

Regan Heath via Digitalmars-d digitalmars-d at puremagic.com
Fri May 9 06:04:47 PDT 2014


On Wed, 07 May 2014 19:41:16 +0100, Maxime Chevalier-Boisvert  
<maximechevalierb at gmail.com> wrote:

>> Unless I'm misunderstanding it should be as simple as:
>>
>> wchar[100] stackws; // alloca() if you need it to be dynamically sized.
>>
>> A slice of this static array behaves just like a slice of a dynamic  
>> array.
>
> I do need it to be dynamically sized. I also want to avoid copying my  
> string data if possible. Basically, I just want to create a wstring  
> "view" on an existing "raw" buffer that exists in memory somewhere,  
> based on a pointer to this buffer and its length.

import std.stdio;
import core.stdc.stdlib : malloc;
import core.stdc.wchar_ : wcscpy;

wchar[] toWChar(const void *ptr, int len)
{
	// Cast pointer to wchar*, create slice (on the heap?) from it (copies no  
data)
	return (cast(wchar*)ptr)[0..len];
}

void main()
{
	// Pre-existing data
	int len = 12;
	wchar *ptr = cast(wchar*)malloc(len * wchar.sizeof);
	wcscpy(ptr, "Hello World");
	
	// Create slice of data
	wchar[] slice = toWChar(ptr, len);
	writefln("%s", slice);
}

R

-- 
Using Opera's revolutionary email client: http://www.opera.com/mail/


More information about the Digitalmars-d mailing list