Windows system casting

Mike Parker via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jun 6 21:06:01 PDT 2016


On Monday, 6 June 2016 at 19:52:36 UTC, Alexander Patapoff wrote:
> import std.stdio;
> import std.string;
> import core.sys.windows.windows;
> void main() {
> 	
> 	string filepath = 
> "C:\\Users\\awpat\\Pictures\\patterns_00387591.jpg";
> 	auto p = toStringz(filepath);
>
> 	int result;
> 	result = SystemParametersInfo(cast(uint)SPI_SETDESKWALLPAPER, 
> cast(uint)0, cast(void*)p ,cast(uint)SPIF_UPDATEINIFILE);
> 	
> }
>
> I'm trying to change the background of my computer. to do this 
> I must convert my string to a const char*, then that can 
> implicitly to a (PVOID). I believe that I am losing all my data 
> in the casting process, is there a way for me to keep my data? 
> or if I am casting this improperly can you demonstrate and 
> explain the proper way to cast to a void pointer (PVOID)?
>

First, Win32 API functions that deal with strings generally come 
in two flavors, such as SystemParametersInfoA and 
SystemParametersInfoW. The A variety deals char strings and the W 
variety deals with UTF16 (wchar in D). By default, the bindings 
in DRuntime alias the non-suffixed names to the W variety, so 
SystemParametersInfo is an alias for SystemParametersInfoW. That 
means you need to use wchar, rather than char for your string 
parameter unless you call SystemParaetmersInfoA explicitly.

Second, string literals in D are always null terminated, so 
there's no need to call toStringz (or std.utf.toUTF16z for wchar 
strings) in this case.

Third, you don't need all of those casts in there. I assume you 
tried it without the casts, saw an error message where all the 
types were different, then applied the casts to all the 
parameters. No need. It's only necessary for the string pointer.

Fourth, while casting the string directly to void* will work, 
it's considered best practice to use the pointer property for 
clarity.

With all of that in mind, either of the following should work for 
you:

// Using string -- note the A suffic on the function name
auto path = "C:\\Users\\awpat\\Pictures\\patterns_00387591.jpg";
auto result = SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, 
cast(void*)path ,SPIF_UPDATEINIFILE);
assert(result);

// Using wstring -- note the w suffix on the string literal
auto path = "C:\\Downloads\\LearningD_Cover.jpg"w;
auto result = SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, 
cast(void*)path ,SPIF_UPDATEINIFILE);
assert(result);




More information about the Digitalmars-d-learn mailing list