Re: char e string em linguagem D

2017-07-13 Thread dark777 via Digitalmars-d-learn

On Thursday, 13 July 2017 at 22:30:29 UTC, crimaniak wrote:

On Thursday, 13 July 2017 at 21:49:40 UTC, dark777 wrote:

Pessoal eu fiz o seguinte programa em C++.

https://pastebin.com/CvVv6Spn

porem tentei fazer o equivalente em D mas nao entendi muito 
bem...


https://pastebin.com/2xw9geRR

alguem poderia me ajudar?


Se acepta utilizar intervalos en lugar de punteros desnudos. 
(Hola, soy traductor de google)


import std.stdio, std.string;

//https://www.vivaolinux.com.br/script/GNU-que-bacana

class GnuQueBacana
{
   this(){}

  char[] stalman()
  {
  return cast(char[])`
  ((__-^^-,-^^-__))
   *---***---*
*--|o   o|--*
   \ /
): :(
(o_o)
  -
 https://www.gnu.org

`;
  }

  char[] torvald()
  {
  return cast(char[])`
#
   ###
   ##O#O##
   ###
   ##\#/##
#lll##
   #l##
   #l###
   #####
  OOO#ll#OOO
 OO#ll#OO
OOO#ll#OOO
 OOO##OOO
https://www.kernel.org

`;
  }

  string stallman()
  {
  return `
  ((__-^^-,-^^-__))
   *---***---*
*--|o   o|--*
   \ /
): :(
(o_o)
  -
 https://www.gnu.org

`;
  }

  string torvalds()
  {
  return `
#
   ###
   ##O#O##
   ###
   ##\#/##
#lll##
   #l##
   #l###
   #####
  OOO#ll#OOO
 OO#ll#OO
OOO#ll#OOO
 OOO##OOO
https://www.kernel.org

`;
  }

};

void main()
{
  GnuQueBacana gnu = new GnuQueBacana();

  writeln(gnu.stalman(), gnu.torvald(), gnu.stallman(), 
gnu.torvalds());

}


muito massa nao achei que era tao simples assim..


Re: nogc string concatenation?

2017-07-13 Thread Nicholas Wilson via Digitalmars-d-learn

On Friday, 14 July 2017 at 00:40:38 UTC, FoxyBrown wrote:

Anyone have an efficient implementation that is easy to use?


If you are OK with just a range spanning the two or more strings, 
then you could use chain as is.


Re: WTF is going on! Corrupt value that is never assigned

2017-07-13 Thread Adam D. Ruppe via Digitalmars-d-learn

On Friday, 14 July 2017 at 00:33:12 UTC, FoxyBrown wrote:
What I'm trying to do is fairly straightforward but I've wasted 
nearly 2 days on it.


//added this so it would all compile
import core.sys.windows.windows;
import core.stdc.stdio;
import core.stdc.stdlib;
import std.stdio;
import std.conv;
import std.array;

pragma(lib, "advapi32");

struct ServiceData
{
wstring Name;
wstring LongName;
int Type;
int State;
int ControlsAccepted;
int Win32ExitCode;
int SpecificExitCode;
int CheckPoint;
int WaitHint;
int ProcessId;
int Flags;
}

auto cstr2dstr(wchar* cstr)
{
import std.array;
auto str = appender!wstring;
auto len = lstrlen(cstr);
str.reserve(len);

for(int i = 0; i < len; i++)
str.put(cstr[i]);

return str.data;
}


auto EnumServices()
{
import core.stdc.stdlib, std.traits;
ServiceData[] servicesList;

	auto buf = malloc(5); // Gets changed later, even though 
never an assignment

auto buf2 = buf; // does not change
auto schSCManager = OpenSCManager(null, null, 
SC_MANAGER_ALL_ACCESS);

if (NULL == schSCManager)
{
printf("OpenSCManager failed (%d)\n", GetLastError());
return servicesList;
}

DWORD dwBytesNeeded, dwCount, lpResumeHandle, resume, totalCount;
	auto servicesType = (SERVICE_DRIVER | SERVICE_FILE_SYSTEM_DRIVER 
| SERVICE_KERNEL_DRIVER | SERVICE_WIN32 | 
SERVICE_WIN32_OWN_PROCESS | SERVICE_WIN32_SHARE_PROCESS);


int cnt = 0;
auto res = 0;
do
{
		// Manually copy over data, this is because EnumSErvicesStatus 
adds data at end of array for some odd ball reason making it 
difficult to build the correct array sequentially

for(int i = 0; i < dwCount; i++)
{
ENUM_SERVICE_STATUS_PROCESS x;
ServiceData d;
			auto s = cast(ENUM_SERVICE_STATUS_PROCESS*)(buf + 
i*ENUM_SERVICE_STATUS_PROCESS.sizeof);

//before buf is of correct value
d.Name = cstr2dstr(s.lpServiceName);
// added these to copy the rest of the fields
d.LongName = cstr2dstr(s.lpDisplayName);
d.tupleof[2 .. $] = s.ServiceStatusProcess.tupleof;
//after buf is invalid, yet buf is never 
assigned


 // added this so it actually appends to array
servicesList ~= d;

}


		res = EnumServicesStatusEx(schSCManager, 
SC_ENUM_TYPE.SC_ENUM_PROCESS_INFO, servicesType, 
SERVICE_STATE_ALL, cast(ubyte*)buf, 5, , 
, , null);
		if (ERROR_MORE_DATA != GetLastError()) { printf("Error 
enumerating services."); break; } 

} while (res == 0);


foreach(s; servicesList)
{
		writeln(s.Name, " - ", s.LongName, " - ", s.Type, " = ", 
s.State);

}


return servicesList;
}

void main() {
EnumServices();
}




I only modified a few lines in there but it works for me on win64.



nogc string concatenation?

2017-07-13 Thread FoxyBrown via Digitalmars-d-learn

Anyone have an efficient implementation that is easy to use?


Re: WTF is going on! Corrupt value that is never assigned

2017-07-13 Thread FoxyBrown via Digitalmars-d-learn

On Thursday, 13 July 2017 at 23:30:39 UTC, Moritz Maxeiner wrote:

On Thursday, 13 July 2017 at 22:53:45 UTC, FoxyBrown wrote:
On Thursday, 13 July 2017 at 20:35:19 UTC, Moritz Maxeiner 
wrote:

On Thursday, 13 July 2017 at 18:22:34 UTC, FoxyBrown wrote:
The following code is pretty screwed up, even though it 
doesn't look like it. I have a buf, a simple malloc which 
hold the results of a win32 call. I am then trying to copy 
over the data in buf to a D struct.


But when copying the strings, the buf location changes, 
screwing up the copying process. It shouldn't happen, buf 
never changes value anywhere except the first malloc(which 
is once). Somehow it is getting changed, but where?


[...]

The buf value changes when calling cstr2dstr but I've had it 
with other values to(any function call such as to!string, 
etc seems to trigger it).


[...]


- Does this happen every time, or only sometimes?
yes, but I've been having this problem and not sure if it was 
quite as consistent as before or that I just recognized it.



- At which loop iteration does it occur?
Now it seems to occur after the first iteration, but I've add 
it happen after a while and in other cases it's worked.. 
depends on if I use malloc, or a D array, or what.



- Which compiler (+version) are you using (with what flags)?
Latest DMD official.. whatever default flags exist in debug 
mode with visual D... why should it matter? [...]


Because it's part of the usual "Steps to reproduce" you are 
supposed to provide so others can verify what you're 
encountering.


- What are the steps to reproduce (i.e. does this e.g. happen 
with a main that consist of one call to EnumServices) ?



Yes, It is basically the first thing I do when I run my 
program. [...]


Okay, I'll setup a Windows VM when I have time and check it out 
(unless someone solves it beforehand).


because D  is not interfacing well with C. First, the win32 
function  does not simply fill in an array but adds additional 
junk at the end(didn't know that until after a few wasted 
hours trying to get it to fill in an array properly).


To be fair, that's neither C nor D fault; that's Microsoft 
providing unintuitive, horrible APIs and doing an amazing job 
of providing documentation (MSDN) that *appears* to be 
exhaustive and well written, but misses all these little 
important details that you actually have to know in order to 
program correct control logic, driving you to the edge of 
sanity. Been there, done that.


I have generally not had that problem. Usually works as it does 
and pretty straight forward. Might have to fish a little for info 
from others but most things have been worked out by someone 
somewhere.


What I'm trying to do is fairly straightforward but I've wasted 
nearly 2 days on it. I had no issues starting or stopping 
services but I can't get the enumerate code to work(the winapi 
function works fine, it's getting the info out of what it passes 
in to D that is the problem). There is no explanation why buf is 
being changed, I never change it after it is initialized, yet, it 
changes somehow. Either it is being overwritten because of a 
pointer that is invalid or it is a stack problem. It is most 
likely the former, but I have tried many different ways and they 
all lead to similar results.





Re: WTF is going on! Corrupt value that is never assigned

2017-07-13 Thread Moritz Maxeiner via Digitalmars-d-learn

On Thursday, 13 July 2017 at 22:53:45 UTC, FoxyBrown wrote:
On Thursday, 13 July 2017 at 20:35:19 UTC, Moritz Maxeiner 
wrote:

On Thursday, 13 July 2017 at 18:22:34 UTC, FoxyBrown wrote:
The following code is pretty screwed up, even though it 
doesn't look like it. I have a buf, a simple malloc which 
hold the results of a win32 call. I am then trying to copy 
over the data in buf to a D struct.


But when copying the strings, the buf location changes, 
screwing up the copying process. It shouldn't happen, buf 
never changes value anywhere except the first malloc(which is 
once). Somehow it is getting changed, but where?


[...]

The buf value changes when calling cstr2dstr but I've had it 
with other values to(any function call such as to!string, etc 
seems to trigger it).


[...]


- Does this happen every time, or only sometimes?
yes, but I've been having this problem and not sure if it was 
quite as consistent as before or that I just recognized it.



- At which loop iteration does it occur?
Now it seems to occur after the first iteration, but I've add 
it happen after a while and in other cases it's worked.. 
depends on if I use malloc, or a D array, or what.



- Which compiler (+version) are you using (with what flags)?
Latest DMD official.. whatever default flags exist in debug 
mode with visual D... why should it matter? [...]


Because it's part of the usual "Steps to reproduce" you are 
supposed to provide so others can verify what you're encountering.


- What are the steps to reproduce (i.e. does this e.g. happen 
with a main that consist of one call to EnumServices) ?



Yes, It is basically the first thing I do when I run my 
program. [...]


Okay, I'll setup a Windows VM when I have time and check it out 
(unless someone solves it beforehand).


because D  is not interfacing well with C. First, the win32 
function  does not simply fill in an array but adds additional 
junk at the end(didn't know that until after a few wasted hours 
trying to get it to fill in an array properly).


To be fair, that's neither C nor D fault; that's Microsoft 
providing unintuitive, horrible APIs and doing an amazing job of 
providing documentation (MSDN) that *appears* to be exhaustive 
and well written, but misses all these little important details 
that you actually have to know in order to program correct 
control logic, driving you to the edge of sanity. Been there, 
done that.


I don't know how any stack corruption could be occurring but 
that is exactly what it looks like. "Return from function call 
and "static variables"(with respect to the call) are changed.". 
But that seems really hard to sell given that it's pretty 
simple and D should have all those basics well covered.


It's always possible for the D compiler to generate wrong code 
(though I'm not convinced that this is the case here), you should 
have a look at the generated assembly.


Re: WTF is going on! Corrupt value that is never assigned

2017-07-13 Thread FoxyBrown via Digitalmars-d-learn

On Thursday, 13 July 2017 at 20:35:19 UTC, Moritz Maxeiner wrote:

On Thursday, 13 July 2017 at 18:22:34 UTC, FoxyBrown wrote:
The following code is pretty screwed up, even though it 
doesn't look like it. I have a buf, a simple malloc which hold 
the results of a win32 call. I am then trying to copy over the 
data in buf to a D struct.


But when copying the strings, the buf location changes, 
screwing up the copying process. It shouldn't happen, buf 
never changes value anywhere except the first malloc(which is 
once). Somehow it is getting changed, but where?


[...]

The buf value changes when calling cstr2dstr but I've had it 
with other values to(any function call such as to!string, etc 
seems to trigger it).


[...]


- Does this happen every time, or only sometimes?
yes, but I've been having this problem and not sure if it was 
quite as consistent as before or that I just recognized it.



- At which loop iteration does it occur?
Now it seems to occur after the first iteration, but I've add it 
happen after a while and in other cases it's worked.. depends on 
if I use malloc, or a D array, or what.



- Which compiler (+version) are you using (with what flags)?
Latest DMD official.. whatever default flags exist in debug mode 
with visual D... why should it matter? buf is changing on the 
only source of that change could be through the winapi call or 
the temp pointer used to index it.. which is never assigned to, 
so it can't be modifying it. The c2d function, when called, 
clearly has no understanding of buff, yet after it returns, it is 
causing the problem. This seems like the stack is being corrupted 
by the function call.



- What are the steps to reproduce (i.e. does this e.g. happen 
with a main that consist of one call to EnumServices) ?



Yes, It is basically the first thing I do when I run my program. 
It is a rather isolated function(Just trying to get a list of 
current services, which has been a total PITA because D is not 
interfacing well with C. First, the win32 function  does not 
simply fill in an array but adds additional junk at the 
end(didn't know that until after a few wasted hours trying to get 
it to fill in an array properly). Hence now I'm trying to convert 
the returned data one iteration at a time rather than all at 
once, but I can't get that to work because the pointer to the 
buffer I created is changing. I could use a temp and get it to 
work, but that doesn't explain what the hell is going on. The 
value of buff seems to be erratic, I've had it point valid 
stuff(other data) and then have small values in it like 8.


I don't know how any stack corruption could be occurring but that 
is exactly what it looks like. "Return from function call and 
"static variables"(with respect to the call) are changed.". But 
that seems really hard to sell given that it's pretty simple and 
D should have all those basics well covered.




Re: char e string em linguagem D

2017-07-13 Thread Basile B. via Digitalmars-d-learn

On Thursday, 13 July 2017 at 22:30:29 UTC, crimaniak wrote:

On Thursday, 13 July 2017 at 21:49:40 UTC, dark777 wrote:
  char[] stalman()
  {
  return cast(char[])`
  ((__-^^-,-^^-__))
   *---***---*
*--|o   o|--*
   \ /
): :(
(o_o)
  -
 https://www.gnu.org

`;
  }



Never cast a literal to char[]. modifying the resulting char[] 
will lead to AV, at least under linux.  `.dup` the literal if you 
really needs char[].


Re: char e string em linguagem D

2017-07-13 Thread crimaniak via Digitalmars-d-learn

On Thursday, 13 July 2017 at 21:49:40 UTC, dark777 wrote:

Pessoal eu fiz o seguinte programa em C++.

https://pastebin.com/CvVv6Spn

porem tentei fazer o equivalente em D mas nao entendi muito 
bem...


https://pastebin.com/2xw9geRR

alguem poderia me ajudar?


Se acepta utilizar intervalos en lugar de punteros desnudos. 
(Hola, soy traductor de google)


import std.stdio, std.string;

//https://www.vivaolinux.com.br/script/GNU-que-bacana

class GnuQueBacana
{
   this(){}

  char[] stalman()
  {
  return cast(char[])`
  ((__-^^-,-^^-__))
   *---***---*
*--|o   o|--*
   \ /
): :(
(o_o)
  -
 https://www.gnu.org

`;
  }

  char[] torvald()
  {
  return cast(char[])`
#
   ###
   ##O#O##
   ###
   ##\#/##
#lll##
   #l##
   #l###
   #####
  OOO#ll#OOO
 OO#ll#OO
OOO#ll#OOO
 OOO##OOO
https://www.kernel.org

`;
  }

  string stallman()
  {
  return `
  ((__-^^-,-^^-__))
   *---***---*
*--|o   o|--*
   \ /
): :(
(o_o)
  -
 https://www.gnu.org

`;
  }

  string torvalds()
  {
  return `
#
   ###
   ##O#O##
   ###
   ##\#/##
#lll##
   #l##
   #l###
   #####
  OOO#ll#OOO
 OO#ll#OO
OOO#ll#OOO
 OOO##OOO
https://www.kernel.org

`;
  }

};

void main()
{
  GnuQueBacana gnu = new GnuQueBacana();

  writeln(gnu.stalman(), gnu.torvald(), gnu.stallman(), 
gnu.torvalds());

}


char e string em linguagem D

2017-07-13 Thread dark777 via Digitalmars-d-learn

Pessoal eu fiz o seguinte programa em C++.

https://pastebin.com/CvVv6Spn

porem tentei fazer o equivalente em D mas nao entendi muito bem...

https://pastebin.com/2xw9geRR

alguem poderia me ajudar?


Re: WTF is going on! Corrupt value that is never assigned

2017-07-13 Thread ag0aep6g via Digitalmars-d-learn

On 07/13/2017 08:22 PM, FoxyBrown wrote:
 res = EnumServicesStatusExW(schSCManager, 
SC_ENUM_TYPE.SC_ENUM_PROCESS_INFO, servicesType, SERVICE_STATE_ALL, 
cast(ubyte*)buf, 5, , , , 
cast(const(char)*)null);


The cast to `char*` here looks odd. The 'W' suffix in the function name 
indicates that it's the UTF-16 variant. It should be taking a `wchar*`, 
not of a `char*`. This might hint at a wrong declaration which could 
lead to memory corruption.


(The cast shouldn't be necessary anyway. `null` converts to all pointer 
types.)


Re: Read from terminal when enter is pressed, but do other stuff in the mean time...

2017-07-13 Thread Moritz Maxeiner via Digitalmars-d-learn

On Thursday, 13 July 2017 at 15:52:57 UTC, Dustmight wrote:
How do I read in input from the terminal without sitting there 
waiting for it? I've got code I want to run while there's no 
input, and then code I want to act on input when it comes in. 
How do I do both these things?


As Stefan mentions, the single threaded version is basically OS 
specific (and as others have said there are some wrappers 
available) the multithreaded solution is fairly simple (have one 
thread blocked on read(stdin), the other working, synchronize as 
necessary).
If you are interested, on Linux one low level (single threaded) 
version would essentially consist of:
- check on program startup whether the stdin file descriptor 
refers to something that (sanely) supports readiness events (tty, 
sockets, pipes, etc. - *not* regular files) using calls like 
`isatty`[1] and co.

- if it's a tty, put it into "raw" mode
- get yourself an epoll instance and register stdin with it
- get a file descriptor, e.g. an eventfd, for "there's work to be 
done now" and register it with the epoll instance
- have the thread wait for readiness events on the epoll instance 
and deal with stdin being readable and "there's work to be done 
now" events for their respective fd.
- Queue work on the eventfd as necessary (e.g. from within the 
readiness handling of the previous step)


[1] http://man7.org/linux/man-pages/man3/isatty.3.html


Re: WTF is going on! Corrupt value that is never assigned

2017-07-13 Thread Moritz Maxeiner via Digitalmars-d-learn

On Thursday, 13 July 2017 at 18:22:34 UTC, FoxyBrown wrote:
The following code is pretty screwed up, even though it doesn't 
look like it. I have a buf, a simple malloc which hold the 
results of a win32 call. I am then trying to copy over the data 
in buf to a D struct.


But when copying the strings, the buf location changes, 
screwing up the copying process. It shouldn't happen, buf never 
changes value anywhere except the first malloc(which is once). 
Somehow it is getting changed, but where?


[...]

The buf value changes when calling cstr2dstr but I've had it 
with other values to(any function call such as to!string, etc 
seems to trigger it).


[...]


- Does this happen every time, or only sometimes?
- At which loop iteration does it occur?
- Which compiler (+version) are you using (with what flags)?
- What are the steps to reproduce (i.e. does this e.g. happen 
with a main that consist of one call to EnumServices) ?


Re: Silly struct behaviour

2017-07-13 Thread H. S. Teoh via Digitalmars-d-learn
On Thu, Jul 13, 2017 at 06:48:27PM +, JN via Digitalmars-d-learn wrote:
> On Thursday, 13 July 2017 at 18:09:46 UTC, H. S. Teoh wrote:
> > 
> > It's not quite so simple. Consider for example:
> > 
> > struct Foo { int bar; }
> > struct Oof { int bar; }
> > 
> > void process(Foo foo) { }
> > void process(Oof oof) { formatDisk(); }
> > 
> > void main() {
> > process({bar : 5}); // which overload should get called?
> > }
> > 
> 
> in this case, I'd expect something like:
> 
> error: ambiguous struct definition, could match process(Foo) or process(Oof)

File an enhancement request:

https://issues.dlang.org/enter_bug.cgi

You never know, we may be able to convince Walter to add this at some
point. :-P


T

-- 
English has the lovely word "defenestrate", meaning "to execute by throwing 
someone out a window", or more recently "to remove Windows from a computer and 
replace it with something useful". :-) -- John Cowan


Re: Silly struct behaviour

2017-07-13 Thread JN via Digitalmars-d-learn

On Thursday, 13 July 2017 at 18:09:46 UTC, H. S. Teoh wrote:


It's not quite so simple. Consider for example:

struct Foo { int bar; }
struct Oof { int bar; }

void process(Foo foo) { }
void process(Oof oof) { formatDisk(); }

void main() {
process({bar : 5}); // which overload should get called?
}



in this case, I'd expect something like:

error: ambiguous struct definition, could match process(Foo) or 
process(Oof)


Re: Silly struct behaviour

2017-07-13 Thread Stefan Koch via Digitalmars-d-learn

On Thursday, 13 July 2017 at 18:45:45 UTC, JN wrote:

I know that's a wrong syntax, I was just showing an example.

Yes, here it will work, but if you want to initialize only some 
fields (poor man's keyword arguments), you can't use the 
default constructor.


easily fixable by using FunctionLiterals.


WTF is going on! Corrupt value that is never assigned

2017-07-13 Thread FoxyBrown via Digitalmars-d-learn
The following code is pretty screwed up, even though it doesn't 
look like it. I have a buf, a simple malloc which hold the 
results of a win32 call. I am then trying to copy over the data 
in buf to a D struct.


But when copying the strings, the buf location changes, screwing 
up the copying process. It shouldn't happen, buf never changes 
value anywhere except the first malloc(which is once). Somehow it 
is getting changed, but where?


The specific win32 or style is irrelevant, I am talking either 
about a bug or some subtle D thing because the code makes sense. 
(Fill Buf, iterate through buffer copying over to D values).


I've ran in to this before, D does something fishy and it wastes 
hours upon hours trying to track done some stupid little thing it 
does.


The buf value changes when calling cstr2dstr but I've had it with 
other values to(any function call such as to!string, etc seems to 
trigger it).





struct ServiceData
{
wstring Name;
wstring LongName;
int Type;
int State;
int ControlsAccepted;
int Win32ExitCode;
int SpecificExitCode;
int CheckPoint;
int WaitHint;
int ProcessId;
int Flags;
}

auto cstr2dstr(wchar* cstr)
{
import std.array;
auto str = appender!wstring;
auto len = lstrlen(cstr);
str.reserve(len);

for(int i = 0; i < len; i++)
str.put(cstr[i]);

return str.data;
}


auto EnumServices()
{
import core.stdc.stdlib, std.traits;
ServiceData[] servicesList;

	auto buf = malloc(5); // Gets changed later, even though 
never an assignment

auto buf2 = buf; // does not change
auto schSCManager = OpenSCManager(null, null, 
SC_MANAGER_ALL_ACCESS);

if (NULL == schSCManager)
{
print("OpenSCManager failed (%d)\n", GetLastError());
return servicesList;
}

DWORD dwBytesNeeded, dwCount, lpResumeHandle, resume, totalCount;
	auto servicesType = (SERVICE_DRIVER | SERVICE_FILE_SYSTEM_DRIVER 
| SERVICE_KERNEL_DRIVER | SERVICE_WIN32 | 
SERVICE_WIN32_OWN_PROCESS | SERVICE_WIN32_SHARE_PROCESS);


int cnt = 0;
auto res = 0;
do
{
		// Manually copy over data, this is because EnumSErvicesStatus 
adds data at end of array for some odd ball reason making it 
difficult to build the correct array sequentially

for(int i = 0; i < dwCount; i++)
{
ENUM_SERVICE_STATUS_PROCESSW x;
ServiceData d;
			auto s = cast(ENUM_SERVICE_STATUS_PROCESSW*)(buf + 
i*ENUM_SERVICE_STATUS_PROCESSW.sizeof);

//before buf is of correct value
d.Name = cstr2dstr(s.lpServiceName);
//after buf is invalid, yet buf is never 
assigned


}


		res = EnumServicesStatusExW(schSCManager, 
SC_ENUM_TYPE.SC_ENUM_PROCESS_INFO, servicesType, 
SERVICE_STATE_ALL, cast(ubyte*)buf, 5, , 
, , cast(const(char)*)null);
		if (ERROR_MORE_DATA != GetLastError()) { print("Error 
enumerating services."); break; } 

} while (res == 0);


for(int i = 0; i < totalCount; i++)
{
auto s = servicesList[i];
		writeln(s.Name, " - ", s.LongName, " - ", s.Type, " = ", 
s.State);

}


return servicesList;
}


Re: Silly struct behaviour

2017-07-13 Thread H. S. Teoh via Digitalmars-d-learn
On Thu, Jul 13, 2017 at 06:07:31PM +, JN via Digitalmars-d-learn wrote:
> Consider:
> 
> struct Foo
> {
>   int bar;
> }
> 
> void processFoo(Foo foo)
> {
> }
> 
> void main()
> {
>   Foo f = {bar: 5};
>   processFoo(f);// ok
>   processFoo(Foo(5));   // ok
>   processFoo({bar: 5}); // fail
>   processFoo(Foo({bar: 5}));// fail
> }
> 
> 
> Wh D? It makes no sense, the compiler knows what is the type of
> the first processFoo arg anyway...

It's not quite so simple. Consider for example:

struct Foo { int bar; }
struct Oof { int bar; }

void process(Foo foo) { }
void process(Oof oof) { formatDisk(); }

void main() {
process({bar : 5}); // which overload should get called?
}

As for `Foo({bar : 5})`, that's just wrong syntax. Just write `Foo(5)`
and it will work.


T

-- 
People demand freedom of speech to make up for the freedom of thought which 
they avoid. -- Soren Aabye Kierkegaard (1813-1855)


Silly struct behaviour

2017-07-13 Thread JN via Digitalmars-d-learn

Consider:

struct Foo
{
int bar;
}

void processFoo(Foo foo)
{
}

void main()
{
Foo f = {bar: 5};
processFoo(f);// ok
processFoo(Foo(5));   // ok
processFoo({bar: 5}); // fail
processFoo(Foo({bar: 5}));// fail
}


Wh D? It makes no sense, the compiler knows what is the type 
of the first processFoo arg anyway...


Re: Read from terminal when enter is pressed, but do other stuff in the mean time...

2017-07-13 Thread Ali Çehreli via Digitalmars-d-learn

On 07/13/2017 08:52 AM, Dustmight wrote:

How do I read in input from the terminal without sitting there waiting
for it? I've got code I want to run while there's no input, and then
code I want to act on input when it comes in. How do I do both these
things?


If you're fine with buffered input, i.e. the user has to press Enter 
before the input is visible to the program, then std.concurrency works 
pretty well.


Enter lines to the following program. It will exit when you send the 
line "done".


import std.concurrency;
import std.stdio;
import core.thread;
import std.range;

struct Done {
}

struct Message {
string line;
}

void worker() {
bool done = false;
while (!done) {
receive(
(Message message) {
auto line = message.line;
writefln("Received \"%s\"", line);
while (!line.empty) {
writeln(line.front);
line.popFront();
Thread.sleep(500.msecs);
}
writefln("Done with \"%s\"", message);
},
(Done message) {
writefln("Bye...");
done = true;
});
}
}

void main() {
auto w = spawn();

foreach (line; stdin.byLineCopy) {
if (line == "done") {
w.send(Done());
break;
}
w.send(Message(line));
}

thread_joinAll();
}

Ali



Re: Read from terminal when enter is pressed, but do other stuff in the mean time...

2017-07-13 Thread NotSpooky via Digitalmars-d-learn

On Thursday, 13 July 2017 at 15:52:57 UTC, Dustmight wrote:
How do I read in input from the terminal without sitting there 
waiting for it? I've got code I want to run while there's no 
input, and then code I want to act on input when it comes in. 
How do I do both these things?


Might want to check Adam's Terminal.d
https://code.dlang.org/packages/arsd-official%3Aterminal
Docs at http://dpldocs.info/experimental-docs/arsd.terminal.html

You can use a RealTimeConsoleInput with getch. You can use kbhit 
to check whether getch would block. However I found inconsistent 
behavior between platforms with kbhit, so might wanna test.


Re: Read from terminal when enter is pressed, but do other stuff in the mean time...

2017-07-13 Thread Stefan Koch via Digitalmars-d-learn

On Thursday, 13 July 2017 at 15:52:57 UTC, Dustmight wrote:
How do I read in input from the terminal without sitting there 
waiting for it? I've got code I want to run while there's no 
input, and then code I want to act on input when it comes in. 
How do I do both these things?


You have to ask the OS for this.
All of this is platform specific functionality.
check your operating-system-api
search terms are unbufferd i/o
and event-loop


Read from terminal when enter is pressed, but do other stuff in the mean time...

2017-07-13 Thread Dustmight via Digitalmars-d-learn
How do I read in input from the terminal without sitting there 
waiting for it? I've got code I want to run while there's no 
input, and then code I want to act on input when it comes in. How 
do I do both these things?


Re: Idiomatic FFT(W) Wrapper

2017-07-13 Thread John Colvin via Digitalmars-d-learn

On Thursday, 13 July 2017 at 12:49:40 UTC, Per Nordlöw wrote:

Have anybody constructed an idiomatic D wrapper for FFTW?


No, sorry, although I have used the library quite a bit in D.


http://www.fftw.org/fftw3_doc/Tutorial.html#Tutorial

I'm specifically concerned about

- `RefCounted`-wrapping of the C structures `fftw_complex` and 
`fftw_plan`


Sounds useful perhaps for fftw_plan. fftw_complex is just 
`typedef double fftw_complex[2];` so I'm not sure what you're 
getting at there.


It's worth remembering that "wisdom" is separate from (and shared 
between) plans in fftw, so constructing and destroying plans can 
be very cheap and there's often no need to have multiple owners 
of a single plan.



- range semantics, lazy evaluation and caching of result in
  stream-based architectures; `fftw_plan`, `fftw_execute`


The discrete fourier transform is a global algorithm that can be 
lazy in input or output, but not both. I'm pretty sure the fast 
fourier transform algorithm for DFT cannot be lazy in either. Do 
you mean creating some sort of lazy short-time-fourier-transform 
(STFT or spectrogram or whatever other name people like)? Or are 
you thinking about 1-D transforms in multi-dimensional data 
(arguably the same thing actually)?



- slicing and scope


??

- seamless interoperability with Mir 
(https://github.com/libmir/mir)


This would definitely be nice to have

For most common use-cases I find fftw is dead simple to use with 
the C API though. So simple that I never even bother making 
bindings, I just declare what I need as I need it (which in a 
single application has never been more than about 10 
declarations).


Idiomatic FFT(W) Wrapper

2017-07-13 Thread Per Nordlöw via Digitalmars-d-learn

Have anybody constructed an idiomatic D wrapper for FFTW?

http://www.fftw.org/fftw3_doc/Tutorial.html#Tutorial

I'm specifically concerned about

- `RefCounted`-wrapping of the C structures `fftw_complex` and 
`fftw_plan`

- range semantics, lazy evaluation and caching of result in
  stream-based architectures; `fftw_plan`, `fftw_execute`
- slicing and scope
- seamless interoperability with Mir 
(https://github.com/libmir/mir)


Re: Why do array literals default to object.Object[]?

2017-07-13 Thread Steven Schveighoffer via Digitalmars-d-learn

On 7/12/17 1:24 AM, Brandon Buck wrote:

On Wednesday, 12 July 2017 at 02:06:41 UTC, Steven Schveighoffer wrote:

I'm sure there's a bug filed somewhere on this...


Is this bug worthy? I can search for one and comment and/or create one 
if I can't find one.


Found it. It was mistakenly closed:

https://issues.dlang.org/show_bug.cgi?id=12283

-Steve


Re: Bad file descriptor in File destructor

2017-07-13 Thread Moritz Maxeiner via Digitalmars-d-learn

On Thursday, 13 July 2017 at 10:56:20 UTC, unDEFER wrote:

Seems I have found. I must do:
try{
File file;
try {
file = File(path);
}
catch (Exception exp)
{
return;
}

//Some actions with file
}
catch (ErrnoException)
{
return;
}


Well, yes, you can also encompass your entire function body in a 
try catch, though that makes your code somewhat hard to read[1]. 
With these many try/catches you may want to take a look at 
std.exception.collectException[2].


[1] https://en.wikipedia.org/wiki/Spaghetti_code
[2] https://dlang.org/phobos/std_exception.html#.collectException


Re: Bad file descriptor in File destructor

2017-07-13 Thread unDEFER via Digitalmars-d-learn
Thank you. I will write if will find the reason of description 
corruption.


Re: 2D game physics, macOS

2017-07-13 Thread Joel via Digitalmars-d-learn

On Thursday, 13 July 2017 at 09:53:05 UTC, Jacob Carlborg wrote:

On 2017-07-13 02:34, Joel wrote:

It doesn't look like there's any thing I can use. I've come 
across: dbox, dchip, and blaze.  Blaze is dsource. dbox is 
alpha and hasn't been updated for 3 years. dchip [1] hasn't 
been updated for 2 years and doesn't compile (that's with out 
using any thing, just import and dub dependency).


You can try creating your own bindings. DStep [1] is a tool 
that can help with that. Make sure you build DStep from master.


[1] http://github.com/jacob-carlborg/dstep


I don't know about trying to do that.


Re: Bad file descriptor in File destructor

2017-07-13 Thread Moritz Maxeiner via Digitalmars-d-learn

On Thursday, 13 July 2017 at 11:15:56 UTC, Moritz Maxeiner wrote:

---
ubyte[File.sizeof] _file;
ref File file() { return *(cast(File*) &_file[0]); }
[create File instance and assign to file]
scope (exit) destroy(file);
---


Forgot to add the try catch:

---
ubyte[File.sizeof] _file;
ref File file() { return *(cast(File*) &_file[0]); }
[create File instance and assign to file]
scope (exit) try destroy(file) catch (ErrnoException) {};
---

or just
---
scope (exit) destroy(file).collectException
---


Re: Bad file descriptor in File destructor

2017-07-13 Thread Moritz Maxeiner via Digitalmars-d-learn

On Thursday, 13 July 2017 at 10:28:30 UTC, unDEFER wrote:
On Thursday, 13 July 2017 at 08:53:24 UTC, Moritz Maxeiner 
wrote:
Where does that `File` come from? If it's std.stdio.File, that 
one is a struct with internal reference counting, so it 
shouldn't crash in the above. Could you provide a minimal 
working (in this case crashing) example?


Yes File is std.stdio.File. And I can't provide a minimal 
crashing example because this code crashes very rarely.


I just want to put try/catch and don't know where to do it.


Well, if you get an ErrnoException on std.stdio.File.~this you 
are AFAIK either encountering an OS bug, or you have previously 
corrupted the file descriptor that File instance wraps around. To 
be specific, it sounds to me like you're trying to close a file 
descriptor that's already been closed, i.e. you should fix that 
instead of trying to work around the consequences of it.
Under the assumption, though, that it's an OS bug you're 
encountering, you can't deal with it with just a try catch in 
that function, because a (stack allocated) struct's destructor is 
always called when it goes out of scope.

I see essentially two workarounds:
- Use two functions foo and bar, where bar has `file` on it's 
stack, and `foo` calls `bar` and catches the destructor exception 
via try catch block around the call to `bar`
- Hide the `file` from the automatic out-of-scope destruction by 
using another type for storage


Personally I'd prefer the second variant, it could look like this:

---
ubyte[File.sizeof] _file;
ref File file() { return *(cast(File*) &_file[0]); }
[create File instance and assign to file]
scope (exit) destroy(file);
---


Re: Bad file descriptor in File destructor

2017-07-13 Thread unDEFER via Digitalmars-d-learn

Seems I have found. I must do:
try{
File file;
try {
file = File(path);
}
catch (Exception exp)
{
return;
}

//Some actions with file
}
catch (ErrnoException)
{
return;
}




Re: Bad file descriptor in File destructor

2017-07-13 Thread unDEFER via Digitalmars-d-learn

On Thursday, 13 July 2017 at 08:53:24 UTC, Moritz Maxeiner wrote:
Where does that `File` come from? If it's std.stdio.File, that 
one is a struct with internal reference counting, so it 
shouldn't crash in the above. Could you provide a minimal 
working (in this case crashing) example?


Yes File is std.stdio.File. And I can't provide a minimal 
crashing example because this code crashes very rarely.


I just want to put try/catch and don't know where to do it.


Re: 2D game physics, macOS

2017-07-13 Thread Jacob Carlborg via Digitalmars-d-learn

On 2017-07-13 02:34, Joel wrote:

It doesn't look like there's any thing I can use. I've come across: 
dbox, dchip, and blaze.  Blaze is dsource. dbox is alpha and hasn't been 
updated for 3 years. dchip [1] hasn't been updated for 2 years and 
doesn't compile (that's with out using any thing, just import and dub 
dependency).


You can try creating your own bindings. DStep [1] is a tool that can 
help with that. Make sure you build DStep from master.


[1] http://github.com/jacob-carlborg/dstep

--
/Jacob Carlborg


Re: Bad file descriptor in File destructor

2017-07-13 Thread Moritz Maxeiner via Digitalmars-d-learn

On Thursday, 13 July 2017 at 08:38:52 UTC, unDEFER wrote:

Hello! I have the code like this:

File file;
try {
file = File(path);
}
catch (Exception exp)
{
return;
}

...
try {

}


Where does that `File` come from? If it's std.stdio.File, that 
one is a struct with internal reference counting, so it shouldn't 
crash in the above. Could you provide a minimal working (in this 
case crashing) example?

If the `File` above is not std.stdio.File, but some custom type:
Be aware that structs have deterministic lifetimes, so `file`'s 
destructor will be called even when you return in the catch 
clause (on the default constructed `file`), so `File`'s 
destructor must check the field carrying the file descriptor for 
being valid; I advise setting such fields to be default 
constructed to some invalid value (e.g. `-1` in case of file 
descriptors).


Re: Bad file descriptor in File destructor

2017-07-13 Thread unDEFER via Digitalmars-d-learn

What the God? I was not ready to post...

File file;
try {
file = File(path);
}
catch (Exception exp)
{
return;
}

try {
//Some actions with file
}
catch (ErrnoException)
{
return;
}


catch (ErrnoException) is necessary because there is sometimes 
"Bad file descriptor" error.
But now I have "Bad descriptior" in destructor. Where I must put 
my try/catch section to avoid it?


Thank you!


Bad file descriptor in File destructor

2017-07-13 Thread unDEFER via Digitalmars-d-learn

Hello! I have the code like this:

File file;
try {
file = File(path);
}
catch (Exception exp)
{
return;
}

...
try {

}


Re: Why do array literals default to object.Object[]?

2017-07-13 Thread Moritz Maxeiner via Digitalmars-d-learn

On Wednesday, 12 July 2017 at 05:24:49 UTC, Brandon Buck wrote:
On Wednesday, 12 July 2017 at 02:06:41 UTC, Steven 
Schveighoffer wrote:



I'm sure there's a bug filed somewhere on this...


Is this bug worthy? I can search for one and comment and/or 
create one if I can't find one.


It's at best very unintuitive behaviour (I had expected the 
inference to go up from the class type to Object, not down from 
Object), so I'd say yes.


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

2017-07-13 Thread John Chapman via Digitalmars-d-learn

On Thursday, 13 July 2017 at 01:15:46 UTC, FoxyBrown wrote:

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, , 
, , cast(const(char)*)null);


You need to call EnumServicesStatusEx twice - the first time to 
get the required size of the buffer. See the docs for the 
lpServices parameter here 
https://msdn.microsoft.com/en-us/library/windows/desktop/ms682640(v=vs.85).aspx


Then allocate a buffer using the returned dwBytesNeeded and call 
the function again with your buffer and its size.


Re: Having a strange issue with std.net.curl.HTTP as a struct dependency

2017-07-13 Thread Ali Çehreli via Digitalmars-d-learn

On 07/13/2017 12:01 AM, Ali Çehreli wrote:

On 07/09/2017 05:10 PM, NoBigDeal256 wrote:


HTTP http;


For what it's worth, defining it as __gshared seems to be a workaround:

__gshared HTTP http;



I sometimes amuse myself. What use is that? :o)

What I must have meant is you can have a __gshared array of those and 
pass pointers to elements to constructors:



__gshared HTTP[] https;

struct ThingA {

HTTP *http;

this(HTTP *http) {
// ...

Not easy but a workaround...

Ali



Re: Having a strange issue with std.net.curl.HTTP as a struct dependency

2017-07-13 Thread Ali Çehreli via Digitalmars-d-learn

On 07/09/2017 05:10 PM, NoBigDeal256 wrote:

> HTTP http;

For what it's worth, defining it as __gshared seems to be a workaround:

__gshared HTTP http;

Ali



Re: Function with static array as parameter

2017-07-13 Thread Miguel L via Digitalmars-d-learn

Thanks for your help.


Re: Static array with parameter based size?

2017-07-13 Thread Miguel L via Digitalmars-d-learn

On Wednesday, 12 July 2017 at 18:49:23 UTC, Jack Applegame wrote:

On Wednesday, 12 July 2017 at 05:45:13 UTC, Miguel L wrote:
Also what is it possible in D to write a function that accepts 
an static array of any size?


void foo(size_t N)(ref int[N] arr) {
...
}

int[10] arr;
foo(arr);


Thank you very much for your answers.