Whats the correct way to pass a D array type to a win32 api function wanting a buffer?

Nicholas Wilson via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jul 12 19:18:54 PDT 2017


On Thursday, 13 July 2017 at 01:15:46 UTC, FoxyBrown wrote:
> Everything I do results in some problem, I've tried malloc but 
> then converting the strings resulted in my program becoming 
> corrupted.
>
>
> Heres the code:
>
> auto EnumServices()
> {
>
>     auto schSCManager = OpenSCManager(null, null, 
> SC_MANAGER_ALL_ACCESS);
>     if (NULL == schSCManager)
>     {
>         print("OpenSCManager failed (%d)\n", GetLastError());
>         return null; // Why can't we return a null? Surely we 
> don't have to cast a null in to a typeof null?
>     }
> 	
> 	import core.stdc.stdlib;
> 	
> 	DWORD dwBytesNeeded, dwCount, lpResumeHandle, resume;
>
> 	auto servicesType = (SERVICE_DRIVER | 
> SERVICE_FILE_SYSTEM_DRIVER | SERVICE_KERNEL_DRIVER | 
> SERVICE_WIN32 | SERVICE_WIN32_OWN_PROCESS | 
> SERVICE_WIN32_SHARE_PROCESS);
>
>
> 	
> 	ENUM_SERVICE_STATUS_PROCESS[5000] services;
> 	auto res = SVC.EnumServicesStatusExA(schSCManager, 
> SC_ENUM_TYPE.SC_ENUM_PROCESS_INFO, servicesType, 
> SERVICE_STATE_ALL, cast(ubyte*)services.ptr, 
> 5000*ENUM_SERVICE_STATUS_PROCESS.sizeof, &dwBytesNeeded, 
> &dwCount, &resume, cast(const(char)*)null);
> 	
> 	
> 	for(int i = 0; i < dwCount; i++)
> 	{
> 		auto s = services[i].lpServiceName;
> 		writeln(*s);				
> 	}
>
>
> 	return services;
> }

What is the signature of the function you are trying to call? 
(make sure its correct :))
Allocating 5000 services may blow your stack.
you can just use `services.sizeof` instead of 
`5000*ENUM_SERVICE_STATUS_PROCESS.sizeof`.
You are returning that massive static array, remember that static 
arrays are value types in D so that will get copied. Consider 
allocating the array and returning a slice of it.

Note also that `lpServiceName` is probably a `char*` so 
drefferencing will give you a char, not a string. Use 
std.string.fromStringz(?) for that.


More information about the Digitalmars-d-learn mailing list