Re: Destructor order
On Wed, 22 Oct 2014 16:49:20 +0100, eles e...@eles.com wrote: On Wednesday, 22 October 2014 at 15:45:02 UTC, eles wrote: D version with structs: { //display ~C~B~A A foo; B bar; C *caz = new C(); delete caz; } as expected. Structs are special, compare: http://dlang.org/struct.html#struct-destructor with: http://dlang.org/class.html#destructors Specifically: The garbage collector is not guaranteed to run the destructor for all unreferenced objects. Furthermore, the order in which the garbage collector calls destructors for unreference objects is not specified. This means that when the garbage collector calls a destructor for an object of a class that has members that are references to garbage collected objects, those references may no longer be valid. This means that destructors cannot reference sub objects. This rule does not apply to auto objects or objects deleted with the DeleteExpression, as the destructor is not being run by the garbage collector, meaning all references are valid. Regan -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: File needs to be closed on Windows but not on Posix, bug?
On Mon, 07 Jul 2014 12:17:34 +0100, Joakim dl...@joakim.airpost.net wrote: On Monday, 7 July 2014 at 10:19:01 UTC, Kagamin wrote: See if stdio allows you to specify delete sharing when opening the file. I don't know what delete sharing is exactly, but the File constructor simply calls fopen and I don't see any option for the Windows fopen that seems to do it: http://msdn.microsoft.com/en-us/library/yeby3zcb.aspx The fopen variant that allows you to specify sharing is: http://msdn.microsoft.com/en-us/library/8f30b0db.aspx But it does not mention delete sharing there. CreateFile allows sharing to be specified for delete however: http://msdn.microsoft.com/en-gb/library/windows/desktop/aa363858(v=vs.85).aspx So... you could: - Call CreateFile giving you a handle - Call _open_osfhandle to get a file descriptor - Call _fdopen on the file descriptor to get a FILE* for it But! I agree with Adam, leave it as a thin wrapper. Being a windows programmer by trade I would expect the remove to fail, I would not expect all my files to be opened with delete sharing enabled by default. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: File needs to be closed on Windows but not on Posix, bug?
On Mon, 07 Jul 2014 15:18:51 +0100, Jesse Phillips jesse.k.phillip...@gmail.com wrote: On Monday, 7 July 2014 at 12:00:48 UTC, Regan Heath wrote: But! I agree with Adam, leave it as a thin wrapper. Being a windows programmer by trade I would expect the remove to fail, I would not expect all my files to be opened with delete sharing enabled by default. R And I believe behavior is still different. In Linux an open file can be accessed even after a delete operation (unlink). But in Windows is that possible? Not sure, I've never done this. It's just not something you would typically want/try to do on windows. If I had to guess, I would say it would still be possible to access the file. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: The writeln() function's args can't be [一 ,二]?
On Tue, 06 May 2014 15:48:44 +0100, Marc Schütz schue...@gmx.net wrote: On Tuesday, 6 May 2014 at 13:35:57 UTC, FrankLike wrote: The problem is that you have a wide-character comma (,) there. This works: void main() { writeln([一, 二]); } No,I mean the execute result is error.That doesn't get the [一, 二],but get the [涓C,浜?]. Why? Thank you. Frank. It works for me (Linux). If you're on Windows, it could have something to do with Windows' handling of Unicode, but I don't know enough about that to help you. There were posts about this in this newsgroup, maybe you can find them, or someone else remembers and can tell you directly... IIRC you need to type chcp 65001 and set the command prompt to the Lucida font... R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: A lot of people want to use D,but they only know MS SQL Server,what will help them to Learn D?
On Thu, 01 May 2014 09:56:49 +0100, FrankLike 1150015...@qq.com wrote: On Monday, 14 April 2014 at 17:13:56 UTC, FrankLike wrote: My advice - use ODBC, it is the fastest way you may connect to the SQL server, and you already have everything you need for that. :) Regards I have test the d\dmd2\windows\lib\odbc32.lib,the size is 4.5kb, I test it by test.d(build :dmd test.d) but find the error: Error 42:Symbol Undefined _SQLFreeHandle@8 Error 42:Symbol Undefined _SQLSetEnvAttr@16 Error 42:Symbol Undefined _SQLAllocHandle@12 Error 42:Symbol Undefined _SQLGetDiagRec@32 -- errorlevel 4 I have fixed the errors. The exe file only 210kb,it works very good. Where the errors is ? In the odbc32.def file. must set the all used function names. such as: _SQLFreeHandle@8 = SQLFreeHandle That's interesting. Those functions are _stdcall, so should be exported from the lib as _func@N. How did you declare them in arsd.mssql? You should use extern(Windows) e.g. extern(Windows) SQLRETURN SQLFreeHandle(SQLSMALLINT HandleType, SQLHANDLE Handle); The extern(Windows) tells DMD to look for _stdcall. extern(C) tells it to look for _cdecl. The difference boils down to who is responsible for cleaning up the stack after a function call. _stdcall assumes the callee will cleanup the stack, _cdecl assumes the caller will. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: std.file.read returns void[] why?
On Wed, 16 Apr 2014 14:36:20 +0100, Spacen Jasset spacenjas...@mailrazer.com wrote: Why does the read function return void[] and not byte[] void[] read(in char[] name, size_t upTo = size_t.max); One one hand the data is always /actually/ going to be a load of (u)bytes, but /conceptually/ it might be structs or something else and using void[] therefore doesn't /imply/ anything about what the data really is. I also thought that void[] was implicitly cast.. but it seems this either has never been the case or was changed at some point: import std.stdio; void main(string[] args) { byte[] barr = new byte[10]; foreach(i, ref b; barr) b = cast(byte)('a' + i); void[] varr = barr; char[] carr; //carr = barr; // Error: cannot implicitly convert expression (barr) of type byte[] to char[] carr = cast(char[])barr; //carr = varr; // Error: cannot implicitly convert expression (varr) of type void[] to char[] carr = cast(char[])varr; writefln(%d,%s, carr.length, carr); } I am curious, was it ever possible, was it changed? why? It's always safe - as the compiler knows how much data the void[] contains, and void[] is untyped so it sorta makes sense to allow it.. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: std.file.read returns void[] why?
On Thu, 17 Apr 2014 13:59:20 +0100, Steven Schveighoffer schvei...@yahoo.com wrote: It was never possible. You must explicitly cast to void[]. to - from? void[] makes actually little sense as the result of whole-file read that allocates. byte[] is at least usable and more accurate. In fact, it's a little dangerous to use void[], since you could assign pointer-containing values to the void[] and it should be marked as NOSCAN (no pointers inside file data). I see what you're saying, byte[] is what *is* allocated.. but my point is that it's not what those bytes actually represent. Are you saying void[] *is* currently marked NOSCAN? However, when using the more conventional read(void[]) makes a LOT of sense, since any T[] implicitly casts to void[]. Indeed. :) R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: Iterate over an array while mutating it?
On Thu, 27 Mar 2014 22:23:40 -, Anh Nhan anhn...@outlook.com wrote: Hey guys, I want to iterate over an array, while adding new entries, and have those in the iteration loop. See here: https://gist.github.com/AnhNhan/9820226 The problem is that the foreach loop seemingly only iterates over the original array, not minding the newly added entries. Does somebody have a solution or approach for the loop to pick up those new entries? Wrap the array in an adapter class/struct which implements opApply for foreach... import std.stdio; import std.conv; struct ForAdd(T) { T[] data; this(T[] _data) { data = _data; } void opOpAssign(string op : ~)(T rhs) { data ~= rhs; } int opApply(int delegate(ref T) dg) { int result = 0; for (int i = 0; i data.length; i++) { result = dg(data[i]); if (result) break; } return result; } } int main(string[] args) { string[] test; for(int i = 0; i 5; i++) test ~= to!string(i); auto adder = ForAdd!string(test); foreach(string item; adder) { writefln(%s, item); if (item == 2) adder ~= 5; if (item == 4) adder ~= 6; if (item == 5) adder ~= 7; } return 0; } R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: GC for noobs
On Thu, 27 Feb 2014 18:29:55 -, Szymon Gatner noem...@gmail.com wrote: On Thursday, 27 February 2014 at 18:06:58 UTC, John Colvin wrote: On Thursday, 27 February 2014 at 14:52:00 UTC, Szymon Gatner wrote: On Thursday, 27 February 2014 at 14:42:43 UTC, Dicebot wrote: There is also one complex and feature-reach implementation of uniqueness concept by Sonke Ludwig : https://github.com/rejectedsoftware/vibe.d/blob/master/source/vibe/core/concurrency.d#L281 (Isolated!T) Priceless for message passing concurrency. Tbh it only looks worse and worse to me :( Another example of code necessary to overcome language limitations. Or, alternatively: A language flexible enough to facilitate library solutions for problems that would normally require explicit language support. I dig flexibility, I really do, and I appreciate D's features that enable that, but in case of such basic thing as a resource management, I just want things to work without surprises by default. Amen. (Not used religiously) I have been around D for a long time, and I have noticed a growing trend of solving problems with clever but complicated library solutions when in *some* cases a simpler built-in solution was possible. I realise Walter's time is precious and I realise that adding complexity to the language itself is something to be generally avoided, but I think sometimes we make the wrong choice. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: Ranges, constantly frustrating
This turned into a bit of a full spec so I would understand if you TL;DR but it would be nice to get some feedback if you have the time.. On Fri, 14 Feb 2014 17:34:46 -, bearophile bearophileh...@lycos.com wrote: Regan Heath: In my case I didn't need any of these. I don't understand. What I meant here is that I don't need the advantages provided by enumerate like the starting index. One thing I am unclear about from your response is what you mean by implicit in this context? Do you mean the process of inferring things (like the types in foreach)? (taken from subsequent reply) Isn't this discussion about adding an index to a range? No, it's not. The counter I want would only be an index if the range was indexable, otherwise it's a count of foreach iterations (starting from 0). This counter is (if you like) an index into the result set which is not necessarily also an index into the source range (which may not be indexable). What we currently have with foreach is an index and only for indexable things. I want to instead generalise this to be a counter which is an index when the thing being enumerated is indexable, otherwise it is a count or index into the result set. Lets call this change scheme #0. It solves my issue, and interestingly also would have meant we didn't need to add byKey or byValue to AA's, instead we could have simply made keys/values indexable ranges and not broken any existing code. Further details of scheme #0 below. (taken from subsequent reply) If you want all those schemes built in a language (and to use them without adding .enumerate) you risk making a mess. In this case explicit is better than implicit. Have a read of what I have below and let me know if you think it's a mess. Scheme #2 has more rules, and might be called a mess perhaps. But, scheme #1 is fairly clean and simple and I think better overall. The one downside is that without some additional syntax it cannot put tuple components nicely in context with descriptive variable names, so there is that. To be fair to all 3 schemes below, they mostly just work for simple cases and/or cases where different types are used for key/values in AA's and tuples. The more complicated rules only kick in to deal with the cases where there is ambiguity (AA's with the same type for key and value and tuples with multiple components of the same type). Anyway, on to the details.. *** Scheme 0) So, what I want is for foreach to simply increment a counter after each call to the body of the foreach, giving me a counter from 0 to N (or infinity/wrap). It would do this when prompted to do so by a variable being supplied in the foreach statement in the usual way (for arrays/opApply) This counter would not be defined/understood to be an index into the object being enumerated necessarily (as it currently is), instead if the object is indexable then it would indeed be an index, otherwise it's a count (index into the result set). I had not been considering associative arrays until now, given current support (without built in tuples) they do not seem to be a special case to me. Foreach over byKey() should look/function identically to foreach over keys, likewise for byValue(). The only difference is that in the byKey()/byValue() case the counter is not necessarily an index into anything, though it would be if the underlying byKey() range was indexable. The syntax for this, is the same as we have for arrays/classes with opApply today. In other words, it just works and my example would compile and run as one might expect. This seems to me to be intuitive, useful and easy to implement. Further, I believe it leaves the door open to having built in tuples (or using library extensions like enumerate()), with similarly clean syntax and no mess. *** So, what if we had built in tuples? Well, seems to me we could do foreach over AAs/tuples in one of 2 ways or even a combination of both: Scheme 1) for AA's/tuples the value given to the foreach body is a voldemort (unnamed) type with a public property member for each component of the AA/tuple. In the case of AA's this would then be key and value, for tuples it might be a, b, .., z, aa, bb, .. and so on. foreach(x; AA) {}// Use x.key and x.value foreach(i, x; AA) {} // Use i, x.key and x.value foreach(int i, x; AA) {} // Use i, x.key and x.value Extra/better: For non-AA tuples we could allow the members to be named using some sort of syntax, i.e. foreach(i, (x.bob, x.fred); AA) {} // Use i, x.bob and x.fred or foreach(i, x { int bob; string fred }; AA) {} // Use i, x.bob and x.fred or foreach(i, new x { int bob; string fred }; AA) {} // Use i, x.bob and x.fred Lets look at your examples re-written for scheme #1 foreach (v; AA) {} foreach (x; AA) { .. use x.value .. } // better? worse? foreach (k, v; AA) {} foreach (x
Re: Ranges, constantly frustrating
On Fri, 14 Feb 2014 02:48:51 -, Jesse Phillips jesse.k.phillip...@gmail.com wrote: On Thursday, 13 February 2014 at 14:30:41 UTC, Regan Heath wrote: Don't get me wrong, counting the elements as you iterate over them is useful, but it isn't the index into the range you're likely after. Nope, not what I am after. If I was, I'd iterate over the original range instead or keep a line count manually. Maybe a better way to phrase this is, while counting may be what you're implementation needs, it is not immediately obvious what 'i' should be. Someone who desires an index into the original array will expect 'i' to be that; even though it can be explained that .take() is not the same range as the original. Thus it is better to be explicit with the .enumerate function. FWIW I disagree. I think it's immediately and intuitively obvious what 'i' should be when you're foreaching over X items taken from another range, even if you do not know take returns another range. Compare it to calling a function on a range and foreaching on the result, you would intuitively and immediately expect 'i' to relate to the result, not the input. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: Ranges, constantly frustrating
On Fri, 14 Feb 2014 13:14:51 -, bearophile bearophileh...@lycos.com wrote: Regan Heath: FWIW I disagree. I think it's immediately and intuitively obvious what 'i' should be when you're foreaching over X items taken from another range, even if you do not know take returns another range. Compare it to calling a function on a range and foreaching on the result, you would intuitively and immediately expect 'i' to relate to the result, not the input. Using enumerate has several advantages. In my case I didn't need any of these. Simple things should be simple and intuitive to write. Yes, we want enumerate *as well* especially for the more complex cases but we also want the basics to be simple, intuitive and easy. That's all I'm saying here. This seems to me to be very low hanging fruit. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: Ranges, constantly frustrating
On Fri, 14 Feb 2014 12:29:49 -, Jakob Ovrum jakobov...@gmail.com wrote: On Friday, 14 February 2014 at 12:10:51 UTC, Regan Heath wrote: FWIW I disagree. I think it's immediately and intuitively obvious what 'i' should be when you're foreaching over X items taken from another range, even if you do not know take returns another range. Compare it to calling a function on a range and foreaching on the result, you would intuitively and immediately expect 'i' to relate to the result, not the input. R How should it behave on ranges without length, such as infinite ranges? In exactly the same way. It just counts up until you break out of the foreach, or the 'i' value wraps around. In fact the behaviour I want is so trivial I think it could be provided by foreach itself, for iterations of anything. In which case whether 'i' was conceptually an index or simply a count would depend on whether the range passed to foreach (after all skip, take, etc) was itself indexable. Also, `enumerate` has the advantage of the `start` parameter, which usefulness is demonstrated in `enumerate`'s example as well as in an additional example in the bug report. Sure, if you need more functionality reach for enumerate. We can have both; sensible default behaviour AND enumerate for more complicated cases. In my case, enumerate w/ start wouldn't have helped (my file was blocks of 6 lines, where I wanted to skip lines 1, 3, and 6 *of each block*) I'm not yet sure whether I think it should be implemented at the language or library level, but I think the library approach has some advantages. Certainly, for the more complex usage. But I reckon we want both enumerate and a simple language solution which would do what I've been trying to describe. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: Ranges, constantly frustrating
On Wed, 12 Feb 2014 11:08:57 -, Jakob Ovrum jakobov...@gmail.com wrote: On Wednesday, 12 February 2014 at 10:44:57 UTC, Regan Heath wrote: Ahh.. so this is a limitation of the range interface. Any plans to fix this? R Did my original reply not arrive? It is the first reply in the thread... It did, thanks. It would be better if this was part of the language and just worked as expected, but this is just about as good. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: Ranges, constantly frustrating
On Wed, 12 Feb 2014 21:01:58 -, Jesse Phillips jesse.k.phillip...@gmail.com wrote: On Wednesday, 12 February 2014 at 10:52:13 UTC, Regan Heath wrote: On Tue, 11 Feb 2014 19:48:40 -, Jesse Phillips jesse.k.phillip...@gmail.com wrote: On Tuesday, 11 February 2014 at 10:10:27 UTC, Regan Heath wrote: Things like this should just work.. File input ... auto range = input.byLine(); while(!range.empty) { range.popFront(); foreach (i, line; range.take(4)) //Error: cannot infer argument types { It isn't *required* to (input/forward), but it could (random access). I think we even have a template to test if it's indexable as we can optimise some algorithms based on this. You chopped of your own comment prompting this response, in which I am responding to a minor side-point, which I think has confused the actual issue. All I was saying above was that a range might well have an index, and we can test for that, but it's not relevant to the foreach issue below. What do you expect 'i' to be? Is it the line number? Is it the index within the line where 'take' begins? Where 'take' stops? If I say take(5) I expect 0,1,2,3,4. The index into the take range itself. I don't see how these two replies can coexist. 'range.take(5)' is a different range from 'range.' Yes, exactly, meaning that it can trivially count the items it returns, starting from 0, and give those to me as 'i'. *That's all I want* 'range may not traverse in index order (personally haven't seen such a range). But more importantly you're not dealing with random access ranges. The index you're receiving from take(5) can't be used on the range. A forward range can do what I am describing above, it's trivial. Don't get me wrong, counting the elements as you iterate over them is useful, but it isn't the index into the range you're likely after. Nope, not what I am after. If I was, I'd iterate over the original range instead or keep a line count manually. Maybe the number is needed to correspond to a line number. Nope. The file contains records of 5 lines plus a blank line. I want 0, 1, 2, 3, 4, 5 so I can skip lines 0, 2, and 5 *of each record*. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: Ranges, constantly frustrating
On Tue, 11 Feb 2014 17:11:46 -, Ali Çehreli acehr...@yahoo.com wrote: On 02/11/2014 06:25 AM, Rene Zwanenburg wrote: On Tuesday, 11 February 2014 at 10:10:27 UTC, Regan Heath wrote: foreach (i, line; range.take(4)) //Error: cannot infer argument types { ..etc.. } foreach (i, line; iota(size_t.max).zip(range.take(4))) { } There is also the following, relying on tuples' automatic expansion in foreach: foreach (i, element; zip(sequence!n, range.take(4))) { // ... } Thanks for the workarounds. :) Both seem needlessly opaque, but I realise you're not suggesting these are better than the original, just that they actually work today. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: Ranges, constantly frustrating
On Tue, 11 Feb 2014 19:48:40 -, Jesse Phillips jesse.k.phillip...@gmail.com wrote: On Tuesday, 11 February 2014 at 10:10:27 UTC, Regan Heath wrote: Things like this should just work.. File input ... auto range = input.byLine(); while(!range.empty) { range.popFront(); foreach (i, line; range.take(4)) //Error: cannot infer argument types { ..etc.. } range.popFront(); } Tried adding 'int' and 'char[]' or 'auto' .. no dice. Can someone explain why this fails, and if this is a permanent or temporary limitation of D/MD. R In case the other replies weren't clear enough. A range does not have an index. It isn't *required* to (input/forward), but it could (random access). I think we even have a template to test if it's indexable as we can optimise some algorithms based on this. What do you expect 'i' to be? Is it the line number? Is it the index within the line where 'take' begins? Where 'take' stops? If I say take(5) I expect 0,1,2,3,4. The index into the take range itself. The reason I wanted it was I was parsing blocks of data over 6 lines - I wanted to ignore the first and last and process the middle 4. In fact I wanted to skip the 2nd of those 4 as well, but there was not single function (I could find) which would do all that so I coded the while above. There is a feature of foreach and tuple() which results in the tuple getting expanded automatically. And also the opApply overload taking a delegate with both parameters. byLine has its own issues with reuse of the buffer, it isn't inherent to ranges. I haven't really used it (needed it from std.process), when I wanted to read a large file I went with wrapping std.mmap: https://github.com/JesseKPhillips/libosm/blob/master/source/util/filerange.d Cool, thanks. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Ranges, constantly frustrating
Things like this should just work.. File input ... auto range = input.byLine(); while(!range.empty) { range.popFront(); foreach (i, line; range.take(4)) //Error: cannot infer argument types { ..etc.. } range.popFront(); } Tried adding 'int' and 'char[]' or 'auto' .. no dice. Can someone explain why this fails, and if this is a permanent or temporary limitation of D/MD. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: Ranges, constantly frustrating
On Tue, 11 Feb 2014 10:52:39 -, Tobias Pankrath tob...@pankrath.net wrote: Further, the naive solution of adding .array gets you in all sorts of trouble :p (The whole byLine buffer re-use issue). This should be simple and easy, dare I say it trivial.. or am I just being dense here. R The second naive solution would be to use readText and splitLines. The file is huge in my case :) R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: Ranges, constantly frustrating
On Tue, 11 Feb 2014 10:58:17 -, Tobias Pankrath tob...@pankrath.net wrote: On Tuesday, 11 February 2014 at 10:10:27 UTC, Regan Heath wrote: Things like this should just work.. File input ... auto range = input.byLine(); while(!range.empty) { range.popFront(); foreach (i, line; range.take(4)) //Error: cannot infer argument types { ..etc.. } range.popFront(); } Tried adding 'int' and 'char[]' or 'auto' .. no dice. Can someone explain why this fails, and if this is a permanent or temporary limitation of D/MD. R Is foreach(i, val; aggregate) even defined if aggr is not an array or associated array? It is not in the docs: http://dlang.org/statement#ForeachStatement import std.stdio; struct S1 { private int[] elements = [9,8,7]; int opApply (int delegate (ref uint, ref int) block) { foreach (uint i, int n ; this.elements) block(i, n); return 0; } } void main() { S1 range; foreach(uint i, int x; range) { writefln(%d is %d, i, x); } } R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: ODBC SQLBindParameter for string array
On Sat, 25 Jan 2014 11:05:11 -, Andre an...@s-e-a-p.de wrote: // CREATE TABLE demo(name VARCHAR(1)) // INSERT INTO demo (name) VALUES (?) string[] stringArr = [A,B,C]; SQLSetStmtAttr(hStmt, SQL_ATTR_PARAMSET_SIZE, cast(SQLPOINTER) stringArr.length, 0); SQLSetStmtAttr(hStmt, SQL_ATTR_PARAM_BIND_TYPE, cast(SQLPOINTER) SQL_PARAM_BIND_BY_COLUMN, 0); SQLINTEGER[] lengIndArr = new SQLINTEGER[](table.rowCount); // Get max length, in this example always: 1 int maxLength = 0; foreach(str;stringArr){ if(str.length maxLength){ maxLength = str.length; } } Try this: // SQLCHAR is defined as ubyte SQLCHAR*[] charArr = new SQLCHAR*[](stringArr.length); foreach(i, str;stringArr){ charArr[i] = cast(SQLCHAR*) toStringz(str); // import std.string lengIndArr[i] = SQL_NTS; // Null terminated string } The SQL API is expecting an array of (C) char* pointers, not an array of D's ubyte[] (which is actually twice the size). SQLBindParameter( hStmt, cast(SQLUSMALLINT) 1, cast(SQLSMALLINT) SQL_PARAM_INPUT, cast(SQLSMALLINT) SQL_C_CHAR, cast(SQLSMALLINT)SQL_VARCHAR, maxLength, 0, charArr[0].ptr, maxLength + 1, // I don't think the +1 is necessary.. lengIndArr.ptr); Regan -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: Slices, appending to arbitrary position
On Mon, 30 Dec 2013 18:40:24 -, Dfr defle...@yandex.ru wrote: Thank you for replies, i think here i can use assoc array, but sometimes it is not suitable because it is not preserve order. What order do you want it in? The index order? If so, iterating over aa.keys.sort() will give you the keys in that order, and you can use that key to get the value aa[key] etc. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: how to detect OS architecture?
On Thu, 19 Dec 2013 09:41:26 -, Marco Leise marco.le...@gmx.de wrote: Am Wed, 18 Dec 2013 13:19:09 - schrieb Regan Heath re...@netmail.co.nz: On Tue, 17 Dec 2013 15:13:20 -, Marco Leise marco.le...@gmx.de wrote: Am Tue, 17 Dec 2013 13:30:25 - schrieb Regan Heath re...@netmail.co.nz: On Mon, 16 Dec 2013 21:27:13 -, Hugo Florentino h...@acdam.cu wrote: On Mon, 16 Dec 2013 20:23:00 +0100, Jacob Carlborg wrote: On 2013-12-16 17:46, Marco Leise wrote: Hehe, I guess the whole purpose of the launcher is to run in 32-bit and detect at runtime if the 64-bit main executable can be run or the 32-bit version must be used. The only advantage of that is that only a 32bit launcher needs to be distributed. Perhaps that's the whole idea. It is. :) Process Explorer by sysinternals, now distributed by M$ does something similar. http://technet.microsoft.com/en-gb/sysinternals/bb896653.aspx It is a 32 bit exe, which detects the OS bit width and if it's 64 bit extracts a 64 exe from within itself to run. When you quit that 64 bit exe, it deletes the file it extracted from disk. It's quite a neat solution. R Only if your executable is self-contained. If you already have external DLLs or assets you can as well have a launcher and 2 actual binaries. I don't see why that changes things? Sure, you cannot extract your *static* dependent dlls (those linked at compile time with libs), those have to exist before you can execute your 32 bit launcher. But, if you really wanted to, you could extract and runtime load dlls no problem. R That's my point. If you really wanted, you could do that but you can as well have a launcher and 2 application binaries and avoid this repeated file extraction/deletion and save yourself some troubles at the end of the day. Sure, but having a self contained exe is useful and *cool* :) R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: how to detect OS architecture?
On Wed, 18 Dec 2013 13:43:44 -, Hugo Florentino h...@acdam.cu wrote: On Wed, 18 Dec 2013 13:20:45 -, Regan Heath wrote: On Wed, 18 Dec 2013 04:22:23 -, Hugo Florentino h...@acdam.cu wrote: On Tue, 17 Dec 2013 15:13:18 +0100, Gary Willoughby wrote: Make sure you handle if users have a 32bit OS installed on a 64bit PC. As a matter of fact that was the actual configuration in the system I wrote the app. I am now with a friend with the same configuration, and it also seems to be working. At work I use Windows 7 x86_64 and it also works. It works because the SYSTEM_INFO member wProcessorArchitecture is defined to be The processor architecture of the installed operating system .. note, *installed operating system*, not processor architecture. Well, isn't that what I needed to begin with? Yes, I was just explaining 'why' it works :) That's why I said OS architecture instead of CPU architecture. Unless you are refering to something else. I was just explaining for posterity/future readers. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: how to detect OS architecture?
On Wed, 18 Dec 2013 04:28:57 -, Hugo Florentino h...@acdam.cu wrote: On Tue, 17 Dec 2013 13:21:30 -, Regan Heath wrote: Is GetNativeSystemInfo your other solution? On the MSDN page for GetNativeSystemInfo it recommends using IsWow64Process to detect if you're running under WOW64, at which point you would then call GetNativeSystemInfo. I am not sure what GetNativeSystemInfo does if called from a 32 bit exe on a 32 bit OS.. It seems to work. After all it makes sense, the native system is actually 32 bits. Cool. The reason I was unsure and the reason I do not agree that it makes sense that it works, is the first paragraph on the MSDN page: Retrieves information about the current system to an application **running under WOW64**. If the function is called from **a 64-bit application**, it is equivalent to the GetSystemInfo function. **emphasis mine** It doesn't actually address the situation of calling it from a 32 bit application NOT running under WOW64. GetSystemInfo is callable from both 32 and 64 bit so I assume now, that given that it works for you, that it is doing what it mentions above for a 64 bit application, and actually just calling GetSystemInfo. You will probably find that calling GetSystemInfo works just as well as what you're already doing. I /know/ that the code in std.internal.windows.advapi32 which dynamically loads and calls IsWow64Process will work, because we use it here at work for this very purpose. It's also the simplest most direct way to answer this specific question and it's already present, tested and working in phobos .. so I would be inclined to use it, in preference over GetNativeSystemInfo. R If after using IsWOW64Process a GetNativeSystemInfo must still be issued like you mentioned earlier, I don't see the advantage over calling that function directly in the first place. Or am I missing something? Yes, you're missing something :) http://msdn.microsoft.com/en-us/library/windows/desktop/ms684139(v=vs.85).aspx IsWow64Process returns (in the output parameter) if the 32 bit application is running in WOW64. WOW64 *only* exists on a 64 bit OS. So, if true this tells you you're on a 64 bit OS. You don't need an additional call to GetNativeSystemInfo at all. Further, the code is already in phobos so all you actually need to do is check the isWow64 global boolean defined by std.internal.windows.advapi32. So, your code is as simple as: import std.stdio; import std.internal.windows.advapi32; void main(string[] args) { writefln(isWow64 ? yes : no); } R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: how to detect OS architecture?
On Tue, 17 Dec 2013 15:13:20 -, Marco Leise marco.le...@gmx.de wrote: Am Tue, 17 Dec 2013 13:30:25 - schrieb Regan Heath re...@netmail.co.nz: On Mon, 16 Dec 2013 21:27:13 -, Hugo Florentino h...@acdam.cu wrote: On Mon, 16 Dec 2013 20:23:00 +0100, Jacob Carlborg wrote: On 2013-12-16 17:46, Marco Leise wrote: Hehe, I guess the whole purpose of the launcher is to run in 32-bit and detect at runtime if the 64-bit main executable can be run or the 32-bit version must be used. The only advantage of that is that only a 32bit launcher needs to be distributed. Perhaps that's the whole idea. It is. :) Process Explorer by sysinternals, now distributed by M$ does something similar. http://technet.microsoft.com/en-gb/sysinternals/bb896653.aspx It is a 32 bit exe, which detects the OS bit width and if it's 64 bit extracts a 64 exe from within itself to run. When you quit that 64 bit exe, it deletes the file it extracted from disk. It's quite a neat solution. R Only if your executable is self-contained. If you already have external DLLs or assets you can as well have a launcher and 2 actual binaries. I don't see why that changes things? Sure, you cannot extract your *static* dependent dlls (those linked at compile time with libs), those have to exist before you can execute your 32 bit launcher. But, if you really wanted to, you could extract and runtime load dlls no problem. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: how to detect OS architecture?
On Wed, 18 Dec 2013 04:22:23 -, Hugo Florentino h...@acdam.cu wrote: On Tue, 17 Dec 2013 15:13:18 +0100, Gary Willoughby wrote: Make sure you handle if users have a 32bit OS installed on a 64bit PC. As a matter of fact that was the actual configuration in the system I wrote the app. I am now with a friend with the same configuration, and it also seems to be working. At work I use Windows 7 x86_64 and it also works. It works because the SYSTEM_INFO member wProcessorArchitecture is defined to be The processor architecture of the installed operating system .. note, *installed operating system*, not processor architecture. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: how to detect OS architecture?
On Mon, 16 Dec 2013 21:26:31 -, Hugo Florentino h...@acdam.cu wrote: On Mon, 16 Dec 2013 17:04:18 -, Regan Heath wrote: ... Compile the launcher as 32bit, and use this global boolean isWow64: ... Thanks, it's nice to have another option. What do you guys think are the possible advantages/disadvantages of either solution? Is GetNativeSystemInfo your other solution? On the MSDN page for GetNativeSystemInfo it recommends using IsWow64Process to detect if you're running under WOW64, at which point you would then call GetNativeSystemInfo. I am not sure what GetNativeSystemInfo does if called from a 32 bit exe on a 32 bit OS.. I /know/ that the code in std.internal.windows.advapi32 which dynamically loads and calls IsWow64Process will work, because we use it here at work for this very purpose. It's also the simplest most direct way to answer this specific question and it's already present, tested and working in phobos .. so I would be inclined to use it, in preference over GetNativeSystemInfo. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: how to detect OS architecture?
On Mon, 16 Dec 2013 21:27:13 -, Hugo Florentino h...@acdam.cu wrote: On Mon, 16 Dec 2013 20:23:00 +0100, Jacob Carlborg wrote: On 2013-12-16 17:46, Marco Leise wrote: Hehe, I guess the whole purpose of the launcher is to run in 32-bit and detect at runtime if the 64-bit main executable can be run or the 32-bit version must be used. The only advantage of that is that only a 32bit launcher needs to be distributed. Perhaps that's the whole idea. It is. :) Process Explorer by sysinternals, now distributed by M$ does something similar. http://technet.microsoft.com/en-gb/sysinternals/bb896653.aspx It is a 32 bit exe, which detects the OS bit width and if it's 64 bit extracts a 64 exe from within itself to run. When you quit that 64 bit exe, it deletes the file it extracted from disk. It's quite a neat solution. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: how to detect OS architecture?
On Mon, 16 Dec 2013 10:53:45 -, Hugo Florentino h...@acdam.cu wrote: I am writing a launcher to make a Windows application portable, but since this application supports both x86 and x86_64, I would like to detect the architecture of the OS my launcher is being run on, in order to launch the proper executable. How can I do this? Compile the launcher as 32bit, and use this global boolean isWow64: import std.stdio; import std.internal.windows.advapi32; void main(string[] args) { writefln(isWow64 ? yes : no); } You can thank Kenji for this one :) Someone document this somewhere please :p The code from advapi32 for those interested.. immutable bool isWow64; shared static this() { // WOW64 is the x86 emulator that allows 32-bit Windows-based applications to run seamlessly on 64-bit Windows // IsWow64Process Function - Minimum supported client - Windows Vista, Windows XP with SP2 alias extern(Windows) BOOL function(HANDLE, PBOOL) fptr_t; auto hKernel = GetModuleHandleA(kernel32); auto IsWow64Process = cast(fptr_t) GetProcAddress(hKernel, IsWow64Process); BOOL bIsWow64; isWow64 = IsWow64Process IsWow64Process(GetCurrentProcess(), bIsWow64) bIsWow64; } Basically, your 32 bit launcher process has to, at runtime, ask Kernel32 for a function IsWow64Process which only exists on 64 bit windows. So, if it doesn't find it, it's 32 bit. If it finds it, it calls it with the current PID to find out of the current process is a 32 bit app running inside WOW64 (the emulator layer) and that gives you the answer. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: How to handle nested structs when converting C headers?
On Thu, 12 Dec 2013 00:04:07 -, H. S. Teoh hst...@quickfur.ath.cx wrote: On Thu, Dec 12, 2013 at 12:54:58AM +0100, Gary Willoughby wrote: On Wednesday, 11 December 2013 at 23:38:13 UTC, Adam D. Ruppe wrote: On Wednesday, 11 December 2013 at 23:35:04 UTC, Gary Willoughby wrote: static union internalRep try static union InternalRep { /* note the capital letter */ /* snip */ } InternalRep internalRep;; // still need a decl Right. But why use the static keyword here? Because nested structs by default carry a pointer to the containing struct (or scope), which means it adds extra baggage and you can't create the nested without also having an instance of the containing struct. I would stop nesting the struct definition. I think that is both cleaner and closer to the original intent - the only reason it is nested in C is because C allows definition and declaration that way, and D does not. Then you don't need static at all. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: Win Headers
On Thu, 12 Dec 2013 08:18:51 -, Mike Parker aldac...@gmail.com wrote: On 12/12/2013 4:44 PM, frustrated2 wrote: thanks for your reply. its a shame that the language does not supply ready to use headers. i can live with missing libraries, but not with incomplete or non working bare minimal prerequisites to use it with an os. that is a sad and sorry state! I don't see why. Win32 bindings aren't shipped with Java or Python and several other languages. Even C and C++, except for maybe one of the MinGW distros. Even with VC, you still have to download the Windows SDK separately. I don't believe this last statement is true. I am fairly certain that upon installing VC you have everything you need to call/use Win32 functions. The only reason to download/install a separate SDK is if your VC version is older and you want a newer SDK/API. Should DMD ship with X-Windows bindings, too? What about Cocoa on OS X? How big are they? If we're just talking about D header files then I am all for it, the more the merrier. It's not like internet bandwidth or hard disk space is currently an issue and it will only become less of an issue the more time rolls on. If people are really anxious about this, why not have a separate download for windows and the various flavours of UNIX.. wait a minute, we already do. :) I would be content if DMD did not ship Win32 bindings at all, except for the minimal needed to implement cross-platform stuff in Phobos. This is more or less the current situation right? Last time I tried to do any Win32 stuff in D there were enormous gaps.. this is one reason I don't have any current projects using D. As it stands, the static libs for the Win32 API that ship with DMD are old and don't include a good number of modern functions anyway. IMO, complete OS API bindings *should* be separate. I wouldn't expect them with the compiler. Sure, if we're talking about DLL/LIB files then I agree, we don't want to be shipping these with the compiler. They should be obtained from official channels i.e. downloading the windows SDK. However.. Does DMD support the M$ dll/lib format or is that still an issue? I know there is a conversion tool, but IIRC you have to pay for that.. this hassle was another reason I stopped using D for my personal projects. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: Win Headers
On Thu, 12 Dec 2013 12:16:57 -, Mike Parker aldac...@gmail.com wrote: On 12/12/2013 8:08 PM, Regan Heath wrote: MinGW distros. Even with VC, you still have to download the Windows SDK separately. I don't believe this last statement is true. I am fairly certain that upon installing VC you have everything you need to call/use Win32 functions. The only reason to download/install a separate SDK is if your VC version is older and you want a newer SDK/API. Oh, I was sure I had to install the SDK when I installed the VC Express. But I see now that it is included. Ah, and I hadn't thought of Express as I've only used Professional etc. Good to know. Should DMD ship with X-Windows bindings, too? What about Cocoa on OS X? How big are they? If we're just talking about D header files then I am all for it, the more the merrier. It's not like internet bandwidth or hard disk space is currently an issue and it will only become less of an issue the more time rolls on. If people are really anxious about this, why not have a separate download for windows and the various flavours of UNIX.. wait a minute, we already do. :) It's not the bandwidth or disk size that bothers me. It's mostly a matter of maintenance. I appreciate the batteries included approach as far as Phobos is concerned, but given that DMD aims to be a cross-platform compiler, I don't think platform-specific API bindings should fall into that category. I mean, all these years and the Win32 bindings are still incomplete, while there are a couple of complete (or mostly complete) third-party bindings out there that do a good job of staying relevant. Why is that? Because Win32 bindings are not a priority for the DMD team. If they aren't a priority, then why ship them? Maintenance is going to depend on community members anyway. Much more efficient, IMO, as a user to use the third-party bindings. It would be different if DMD were Windows-centric, or if it didn't have a platform abstraction in the form of Phobos. Platform API bindings basically provide system functions and GUI functions. IMO, let Phobos abstract away the system and third-party libs abstract away the GUI. Beyond that, I can't imagine that those needing direct API access beyond a handful of functions will be more than a minority. So for them, let third-parties handle the API bindings too. I haven't done any straight-up Win32 development in years and when I do need a Win32 function, it's usually one that isn't available in the ancient libs DMD ships so I have to prototype it and load it manually anyway. But if I do need more of the Win32 API, then I have no problem using an external lib for it. Especially if that lib supports dub. Fair enough, I hadn't thought of it from that perspective. I agree, maintenance would not, and should not be a high priority for the maintainers of D/MD. The issue for me is then one of perception and hassle. If I am a new windows based D user and I download the installation and immediately struggle to interface with Win32 I might make the effort to go looking for these third-party bindings, I might find one which has what I need, and I might manage to get it working but that is a lot more hassle than it could be, it is enough hassle that some people might simply give up at this point - especially existing C/C++ users who have it easy currently. There is a totally different mentality in the windows world, we are far too used to everything just working out of the box. I absolutely detest the (I suspect somewhat less common than last time I had to do this) UNIX-land practice of having to download and compile dependency after dependency just to get something simple working. The same perception applies to programming languages and libraries, tho programmers are more likely to stick at it if for nothing other than the challenge it represents. So.. I think D ought to give it's blessing to one third-party Win32 library and link it prominently on the download page at the very least (apologies if this is not already the case but I haven't looked in a while), even better would be a mechanism where the installation itself would automatically obtain the library (using dub perhaps) if selected by the user. The same argument applies to other platforms and SDKs, in an ideal world they would all be downloaded/installed by the DMD installation if selected by the user. The same applies to GUI libraries, I think a vanilla Win32 GUI library needs to exist and be prominently linked or included via the installation. I think many new D users are turned off by the task of trying to piece all this together right off the bat. I realise this is a fair bit of work, but I think lowering the bar for entry should be a very high priority as the more people we can get on board the better and the sooner the better. More people means more exposure and more
Re: Small troubles with private
On Tue, 05 Nov 2013 16:00:41 -, bearophile bearophileh...@lycos.com wrote: 1) I usually write more than one class or struct inside each D module, unlike in Java. But sometimes when I move that class or struct elsewhere (during refactoring, or in other situations) I get access errors to private fields. Those errors were already in my code, but I didn't see them because private in D means module-private. 2) My unittests are useful to catch bugs when I run them at run-time, but they are also use to exercise code, this means to actually use it, and catch some bugs statically (instantiating templates, etc). But unfortunately such unittests can't catch protection bugs because most of my unittests are inside the same module, so private gets ignored. 3) A third problem with module-private is that newbies coming from Python, C, and other languages that don't have private/protected attributes and write little experimental D programs, have less chances to _learn_ the true semantics of the privacy attributes until they start to spread their classes in different modules. How to solve such little troubles? A possible idea is to add to D another attribute, a kind of private private that is enforced inside the same module. It could be named super private because D has the super keyword :-) But this idea doesn't solve all the problems, because sometimes you don't want to use a super private attribute. I think a compiler flag is the best option. The flag would cause warnings to appear for each violation of strict privacy between classes in the same module. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: How to cleanup after Socket.bind on Linux?
On Tue, 27 Aug 2013 04:30:10 +0100, Ali Çehreli acehr...@yahoo.com wrote: The following simple socket example is trying to cleanup after itself, except the bind() call. As I repeat in the QUESTION comment below, I have read the man page of bind and I know that I need to unlink a path. How can I get that path? That example is for AF_UNIX domain sockets. TcpSocket is an AF_INET domain socket. In AF_INET there is no 'path' and there is nothing you need to do to cleanup after bind - other than close the socket. I do not believe a shutdown is required for a listening socket - tho don't quote me on that. The problem is, currently the program apparently leakes some resources. It cannot be started a second time for 8080 still being in use, unless you wait for several seconds, presumably until the OS does the cleanup. Correct. And this time varies by platform, as dnewbie mentions on Windows you can re-use immediately. You could set the REUSE option on the socket prior to 'bind', this would allow you to bind again while the previous socket was in cleanup. The other thing which might be affecting things is.. Take a look at: http://linux.die.net/man/7/socket Specifically SO_LINGER. This socket option controls whether and how long a socket will linger after it is closed. I am not sure what the linux defaults are for that, but it may be set to linger intentionally. You could use getsockopt to obtain the LINGER default values and see. Also.. the sentence When the socket is closed as part of exit(2), it always lingers in the background. made me think, when does scope(exit) fire? Does it occur as part of exit in your example? Does manually calling shutdown/close on the listening socket resolve the issue. Regan -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: Order matters on inheritance
On Thu, 22 Aug 2013 02:43:42 +0100, JS js.m...@gmail.com wrote: I don't know what the expected behavior is but it seems odd/wrong: http://dpaste.dzfl.pl/a390f1f4 Note that there are two issues here(almost the same). First is that A.foo isn't called and second is that the order of inheritance on A matters(: X, Y vs : Y,X). I would expect that A.foo(A) should match first and the ambiguity created from the inheritance should result in an error. I disagree that a.foo(A) should match, because.. You have a variable 'q' of type (interface) 'A' and you call method 'foo' on it. The compiler MUST only consider methods available on type (interface) 'A', which are: foo(X) foo(Y) It cannot call a.foo(A) (note 'a.foo' not 'A.foo') because while 'q' does in reality refer to an object of type 'a', you've asked it to interface to it via it's interface 'A' which does not have an overload foo(A). I do however agree that the compiler behaviour of silently selecting the foo from the first interface listed is wrong, it ought to give an error in this case IMO. Regan -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: Style question
On Thu, 11 Jul 2013 19:22:10 +0100, Namespace rswhi...@googlemail.com wrote: I have a style question, because a friend of mine has a similar problem currently and I have no good advice for him. Let's assume we have this classes: class MyClass { public: enum A { Foo = 0, Bar = 1 } private: A _a; public: this(A a) { this._a = a; } void test1() { MyStaticClass.test2(this._a); } } // enum B { Foo = 0, Bar = 1 } final abstract class MyStaticClass { public: static void test2(B b) { } } void main() { } Prints: Error: function enum_problem.MyStaticClass.test2 (B b) is not callable using argument types (A) What should he do? If A and B are supposed to be/represent the same thing, then they should be the same enumeration - move them/it into a separate module and import into both MyClass and MyStaticClass. If they're supposed to be different, then you treat them as separate types and either cast, or range check then cast. So, add a uint constructor to MyStaticClass (in addition to the existing B constructor). Have the uint constructor range check the value using assert, or exceptions, then cast valid values to B internally. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: Can someone give me a little program design advice please?
On Sun, 16 Jun 2013 16:27:27 +0100, Gary Willoughby d...@kalekold.net wrote: I'm writing a little program in D to perform some database operations and have a small question about design. Part of my program watches a log file for changes and this involves code which is wrapped up in a class. So the usage is something like this: auto fileWatcher = new FileWatcher(fileName); fileWatcher.onChange(delegate); fileWatcher.start(); Once the start method is called a loop is entered within the class and the file is watched. Changes are handle through calling the registered delegate. The loop uses different watch methods for different platforms. What i need to be able to do is to stop the current watch and change the watched file. Because this is in an infinite loop, i can't check externally i.e. outside of the class, if i need to break from the loop simply because control never returns to the caller of the start() method. I would derive FileWatcher from Thread: http://dlang.org/phobos/core_thread.html#.Thread So, now control does return to the caller - so you can create these in you main control thread before going off to do other things. Note that Thread does not have a stop() method. This is likely because ruthlessly terminating a thread is generally frowned upon. Instead you 'ask' the thread nicely to stop (first). My preferred method of doing this is to have a boolean loop control variable, plus an event. So your main thread loop checks the loop control variable, and when the thread wants to sleep/wait for any reason it waits on the event. In this way you can instantly wake it up by setting the event, and you can instantly stop it by setting the loop control variable and waking it up. e.g. class FileWatcher : Thread { private: bool stopping; event sleepEvent; void run() { while (!stopping) { // ..your main loop code here.. // if you need to wait/sleep wait on sleepEvent // always check stopping after waiting/sleeping if your loop processes more after this if (stopping) break; // ..more loop code here.. } } public: void stop() { stopping = true; set the event } } R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: [Doubt] Variadic arguments as reference (Possible?)
On Fri, 14 Jun 2013 13:55:29 +0100, MattCoder mattco...@gmail.com wrote: I want to know if there is a way to pass variadic arguments as reference? DMD says no! import std.stdio; import std.conv; void sum(double value, double*[] numbers ...){ foreach(ref num; numbers) *num = *num + value; } void main(){ double a = 1, b = 2, c = 3; sum(10, a, b, c); writeln(a = ~to!string(a), \nb = ~to!string(b), \nc = ~to!string(c)); } R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: std.traits functions causing the compiler to crash
On Sat, 08 Jun 2013 05:52:49 +0100, Eric e...@makechip.com wrote: On Saturday, 8 June 2013 at 02:32:57 UTC, bearophile wrote: Eric: Yes, the template constraint is much better. However, the compiler still crashes, even with the new code: Because there's a type definition loop, regardless. Using a constraint doesn't change that situation. Bye, bearophile How is there a type definition loop? I'm just trying to constrain the interface. At a minimum this should be a compiler bug, but I would hope that dimple constraints would work. There is a type loop but I agree the compiler should really be able to catch it. Using bearophile's short example.. import std.traits: hasMember; interface Xidentity(V, K) if (!hasMember!(V, x)) { } class Foo(K): Xidentity!(Foo!K, K) { K x; } void main() { new Foo!double; } The compiler starts by generating the template for Foo(double), requiring Xidentity(Foo!double,.. requiring Foo(double), requiring Xidentity(Foo!double,.., and so on.. It should really be able to detect that it is re-generating the original Foo(double) and simply re-use/terminate the loop there, I think. (I am no compiler expert however) R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: and/or/not/xor operators
On Tue, 04 Jun 2013 23:47:07 +0100, ixid nuacco...@gmail.com wrote: On Monday, 3 June 2013 at 09:29:20 UTC, Regan Heath wrote: On Fri, 31 May 2013 21:26:56 +0100, ixid nuacco...@gmail.com wrote: We really don't want D to become a TMTOWTDI language. Ideally there should be 1 right way and no alternatives. That way, anyone who knows D will have a greater chance of knowing what any given code sample does, and not have to look up alternate syntax etc. R Up to a point I'd certainly agree with that, however in this case I think the advantages outweigh the penalty. Not for me, and I suspect others too. These operators are self-documenting, no one will need to look up 'and' I can't recall ever being confused by .. in fact, I got my first programming job (an apprentice position) by describing some C code (a language I had never used/seen before) using and I immediately guess what it meant, it was obvious from the context. and gain readability To me using and would reduce parsability (as in by my human eyes) and that would hamper readability, for me. language accessibility Any programmer that does not understand needs to be educated, period. Once that happens they can code in numerous other languages, so win-win. beauty. I don't find ugly, in fact I would go so far as to say that code using and would be less pleasant to my eyes. R I think you're coming from a position of what is rather than what can be. You're practiced with so it appears more normal than it is. Yes. I am, and every other C and C++ programmer is. Just about no-one is practiced with and or or in a programming language. a and b is far clearer than a b No, it's really not (for me). especially as you add more terms: a and b or c versus a b || c The latter is still clearer (to me). R
Re: and/or/not/xor operators
On Fri, 31 May 2013 21:26:56 +0100, ixid nuacco...@gmail.com wrote: We really don't want D to become a TMTOWTDI language. Ideally there should be 1 right way and no alternatives. That way, anyone who knows D will have a greater chance of knowing what any given code sample does, and not have to look up alternate syntax etc. R Up to a point I'd certainly agree with that, however in this case I think the advantages outweigh the penalty. Not for me, and I suspect others too. These operators are self-documenting, no one will need to look up 'and' I can't recall ever being confused by .. in fact, I got my first programming job (an apprentice position) by describing some C code (a language I had never used/seen before) using and I immediately guess what it meant, it was obvious from the context. and gain readability To me using and would reduce parsability (as in by my human eyes) and that would hamper readability, for me. language accessibility Any programmer that does not understand needs to be educated, period. Once that happens they can code in numerous other languages, so win-win. beauty. I don't find ugly, in fact I would go so far as to say that code using and would be less pleasant to my eyes. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: and/or/not/xor operators
On Fri, 31 May 2013 02:41:14 +0100, Shriramana Sharma samj...@gmail.com wrote: Thanks to all who replied. On Thu, May 30, 2013 at 10:18 PM, bearophile bearophileh...@lycos.com wrote: But Walter refused them time ago on the basis that no one uses them in C++. So you can ask for them in the main D newsgroup, but I don't think you will see them in D... Um why really? No one uses them in C++? How come? Until this thread I didn't even know they existed.. and I've been coding in C++ for ~12 years. I suspect people who came to C++ from C (as I did) would not learn about them, because they are simply alternate syntax for something they already know and use. I find them ugly and less clear - because I can glance at words symbols and immediately see the operator, faster than with words and symbols. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: Writing closed source programs in D?
On Fri, 31 May 2013 12:25:48 +0100, Shriramana Sharma samj...@gmail.com wrote: Now I'm *not* going to write closed source programs in D [;-)], but am curious -- in C++ we have header files which a developer can confidently distribute along with the compiled libraries, and the actual source of the libraries (the *.cpp files) remains with the developer. In D, (obviously I'm a noob) it seems that module is the unit of programming, so how does one provide the library user with an API only without distributing the full D sources? Is it perhaps like Python where you can compile stuff into a SO and provide appropriate documentation so the user can just do import fooclosedlib and go ahead? You ship the library with .di files created by the compiler. http://dlang.org/dmd-linux.html#interface_files .di files are .d files without the function bodies etc. There are issues with templates and auto, but we will eventually have nice solutions for those. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: Producing library files from D
On Fri, 31 May 2013 12:26:54 +0100, Shriramana Sharma samj...@gmail.com wrote: Hello. How do I make a library from D? I see the dmd --help output give a -lib option but am not sure how to actually use it. Can I produce a library and then just import it by its name? (This is an offshoot of my previous query about the proprietary lib thing.) And given that http://dlang.org/cpp_interface.html talks about compiling a C++ file with a C++ compiler and a D file with a D compiler and then linking the two together, do I understand something like: clang -c cpplib.cpp dmd -c dprog.d ld -o d-cpp-joint-venture cpplib.o dprog.o -lm What do I do to create a sharedlib/staticlib which would have both C++ and D objfile components? Is it the regular: ld -shared -o $(SHAREDLIB) $(OBJFILES) -lm and ar r $(STATICLIB) $(OBJFILES) ranlib $(STATICLIB) IOW, after dmd finishes compiling, it is just like any other object file on my platform? Thanks as ever for your patience! Have you seen this: http://dlang.org/dmd-linux.html#library R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: My first D program
On Thu, 30 May 2013 12:13:19 +0100, Shriramana Sharma samj...@gmail.com wrote: Hello. I am new to D and come from some intermediate C/C++ plus some Python programming background. I currently have DMD 2.062 installed on my Kubuntu Raring 64-bit system. 1. Too big binary output? OK so I wrote my first Hello World program: #! /usr/bin/rdmd import std.stdio ; void main() { writeln ( Namaste Prapancha! ) ; } (so I'm a bit of a Sanskrit geek...) and when I save it as namaste.d, do chmod +x and run ./namaste.d, all is fine and I get the output. However I am somewhat taken aback to see the file size -- 335KiB for a simple Hello World? The equivalent C/C++ programs compiled with Clang without any -O options produce binaries of less than 10K! The D standard library is currently statically linked. This will change shortly/eventually. 2. No filename freedom? Next I wanted to go to another example but I like to keep my practice files in order, so I rename namaste.d to 01-namaste.d but I get the error: $ dmd 01-namaste.d 01-namaste.d: Error: module 01-namaste has non-identifier characters in filename, use module declaration instead Huh? Now my program *name* has to be a valid identifier in the language? So I can't have my filename contain a hyphen-minus or start with a digit, and only something like e01_namaste.d is permitted. Why is this? As the error says use module declaration instead. You need to add a module namaste; statement to the top of the file 01-namaste.d. D defaults the module name to the filename, but you can specify it when they differ. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: WinAPI callbacks and GC
On Tue, 07 May 2013 00:03:58 +0100, Sean Kelly s...@invisibleduck.org wrote: On May 2, 2013, at 6:17 AM, Regan Heath re...@netmail.co.nz wrote: On Wed, 01 May 2013 01:12:39 +0100, Sean Kelly s...@invisibleduck.org wrote: On Apr 23, 2013, at 2:21 PM, Jack Applegame jappleg...@gmail.com wrote: According WinAPI documentation, CtrlHandler will be called in new additional thread. Is it safe to allocate GC memory in NOT Phobos threads? If not, how to make it safe? I'm trying call thread_attachThis() at the beginning of CtrlHandler fucntion, but it doesn't compile because thread_attachThis() is not no throw. thread_attachThis should probably just be labeled nothrow. I don't think there's anything in that function that can throw an Exception. That makes it callable.. but did you see my post about the various timing issues with using this in a non-GC thread (potentially while the GC is already collecting - or similar). The GC holds a lock on the global thread list while collecting, so it shouldn't be possible for thread_attachThis to register a thread when this is happening. In fact, thread_attachThis even temporarily disables the GC, and since this operation is protected by the GC lock, it's blocked there as well. Excellent. Might be nice to see some of these details in the docs :p .. or even just a will block if collection is in progress. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: WinAPI callbacks and GC
On Wed, 01 May 2013 01:12:39 +0100, Sean Kelly s...@invisibleduck.org wrote: On Apr 23, 2013, at 2:21 PM, Jack Applegame jappleg...@gmail.com wrote: According WinAPI documentation, CtrlHandler will be called in new additional thread. Is it safe to allocate GC memory in NOT Phobos threads? If not, how to make it safe? I'm trying call thread_attachThis() at the beginning of CtrlHandler fucntion, but it doesn't compile because thread_attachThis() is not no throw. thread_attachThis should probably just be labeled nothrow. I don't think there's anything in that function that can throw an Exception. That makes it callable.. but did you see my post about the various timing issues with using this in a non-GC thread (potentially while the GC is already collecting - or similar). R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: WinAPI callbacks and GC
On Tue, 23 Apr 2013 22:21:27 +0100, Jack Applegame jappleg...@gmail.com wrote: I'm writing Ctrl-C handler for console application for Windows: extern(Windows) { int CtrlHandler(uint flag) nothrow { auto tmp = new SomeClass; // is it safe? ... return true; } } ... SetConsoleCtrlHandler(CtrlHandler, true); ... According WinAPI documentation, CtrlHandler will be called in new additional thread. Is it safe to allocate GC memory in NOT Phobos threads? If not, how to make it safe? I'm trying call thread_attachThis() at the beginning of CtrlHandler fucntion, but it doesn't compile because thread_attachThis() is not nothrow. You are correct in that the issue with this handler is that it's likely called in a thread created by the Win32 runtime which the D GC has no knowledge of. And, because of this wont get paused when the GC runs a collection, which is an issue because your allocation above might happen during a GC collection, and the GC is likely to have an 'issue' with it. The issue here is a timing window. Lets assume the GC is busy performing a collection when the handler runs. If you wrap the thread_attachThis() in a try/catch block as evilrat has shown this should solve the nothrow issue. But, the GC is unlikely to then pause your thread - because it's already done the thread pausing and is busy marking and sweeping so your thread will continue to run and allocate during collection. The other idea is to call GC.disable() to disable automatic collection at the start of the handler, and GC.enable() at the end. But again, if collection has already started this might not work, might fail horribly, and wont protect you. Someone needs to check the GC code, and thread_attachThis to see if it can handle the situation you've presented. Until then, I would perform manual memory allocation. I am not sure how in D, but you need something like placement new to construct a class in a previously allocated block of memory (allocated with malloc or similar). R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: Ref and class function calls?
On Tue, 16 Apr 2013 18:51:06 +0100, Tofu Ninja emmo...@purdue.edu wrote: On Tuesday, 16 April 2013 at 15:23:56 UTC, Regan Heath wrote: I would question always question fully intended on a case by case basis: http://www.drdobbs.com/cpp/how-non-member-functions-improve-encapsu/184401197 I agree that grouping functions together that should be used together, or on the same type of object is a good idea from an organisational point of view but that shouldn't be the only reason for making them class member functions. R I think a lot of people give too much credit to encapsulation. I mean don't get me wrong its cool and all and it has its place, but it seems like some people make it seem a lot more important than it really is. I mean having lots of encapsulation really doesn't do anything for your program, it won't run faster or do more things. If any thing, more often than not, it makes things run slower, as you can't see what's in the black box. Thats just my opinion on the whole thing... True, but this is what I'd call a short term view of encapsulation and code quality. Thinking about encapsulation in the short term is important because it forces you to properly design things for the long term. If you don't care at all about encapsulation (or orthogonality) you probably wont bother to actually define the interface between two potentially orthogonal pieces of code. If there is no separation designed in to start with then code tends to tie itself together in sometimes surprising ways typically creating unintended dependencies or complexity. Essentially the code becomes harder to reason about, harder to change and therefore harder to improve. So, ultimately encapsulation (one aspect of good design) should lead to code which is better in every measurable way, including running faster. Sure, there will be the odd case where encapsulation decreases performance, in those cases I would take the practical route of breaking encapsulation to solve the issue. In short, encapsulation is important and useful but not paramount. :) R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: Ref and class function calls?
On Wed, 17 Apr 2013 12:02:25 +0100, Regan Heath re...@netmail.co.nz wrote: So, ultimately encapsulation (one aspect of good design) should lead to code which is better in every measurable way, including running faster. It may not have been 100% clear what I was implying here. Because encapsulation makes the code easier to reason about, it makes it easier to change, and improve. Therefore, it's easier to improve the performance of the code. That, plus the idea that you can and should break encapsulation for a higher priority concern - which may be performance for example - mean that encapsulation should not negatively impact any code base. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: Ref and class function calls?
On Wed, 17 Apr 2013 12:17:03 +0100, Tofu Ninja emmo...@purdue.edu wrote: On Wednesday, 17 April 2013 at 11:02:24 UTC, Regan Heath wrote: True, but this is what I'd call a short term view of encapsulation and code quality. Thinking about encapsulation in the short term is important because it forces you to properly design things for the long term. If you don't care at all about encapsulation (or orthogonality) you probably wont bother to actually define the interface between two potentially orthogonal pieces of code. If there is no separation designed in to start with then code tends to tie itself together in sometimes surprising ways typically creating unintended dependencies or complexity. Essentially the code becomes harder to reason about, harder to change and therefore harder to improve. So, ultimately encapsulation (one aspect of good design) should lead to code which is better in every measurable way, including running faster. Sure, there will be the odd case where encapsulation decreases performance, in those cases I would take the practical route of breaking encapsulation to solve the issue. In short, encapsulation is important and useful but not paramount. :) R You misunderstand me, I think encapsulation is great and important, but just not as great and important as a lot of people seem to think. No, I got all that :) My point was that it can in fact make your program run faster, indirectly. :P R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: Ref and class function calls?
On Tue, 16 Apr 2013 15:57:09 +0100, Tofu Ninja emmo...@purdue.edu wrote: On Tuesday, 16 April 2013 at 14:33:21 UTC, John Colvin wrote: A member function cannot modify it's own 'this' pointer. However, a free function can do it happily, which when combined with UFCS gives you the same syntax and behaviour: class A { //.. } void replace(ref A a) { a = new A(); } void main() { A a = new A(); A b = a; assert(b is a); b.replace(); assert(!(b is a)); } http://dpaste.dzfl.pl/147f69e1 Yes... this is what I feared. I knew I could do it like that but I was hoping a more elegant solution was available, seems like bad design to have a function that is fully intended to be a class function but not actually be able to declare it within the class block. I would question always question fully intended on a case by case basis: http://www.drdobbs.com/cpp/how-non-member-functions-improve-encapsu/184401197 I agree that grouping functions together that should be used together, or on the same type of object is a good idea from an organisational point of view but that shouldn't be the only reason for making them class member functions. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: SocketStream and weird 0xA character
On Sun, 17 Feb 2013 16:53:23 -, Lubos Pintes lubos.pin...@gmail.com wrote: I am writing little program which downloads simple data file from server through HTTP. The file is static, but updated regularly, so I am using Range: bytes header to optimize the traffic a bit. After I analyzed HTTP status line and headers, I started to read the raw data through SocketStream.read(buffer). There seems to be one single '\n' character in buffer[0] after first read. I cannot figure out why this character is appearing. It is not there when I download that file through wget. Here is relevant part of code: //Parse status line + headers string[string] header; auto line=ss.readLine(); auto statusLine=line.split( ); auto responseCode=to!int(statusLine[1]); while(true) { line=ss.readLine(); if(!line.length) break; auto h=line.split(:); header[h[0].idup]=h[1].strip.idup; } int contentLength=to!uint(header[Content-Length]); if(responseCode==416 contentLength==fileSize) return; //nothing to download if(responseCode==200 || responseCode==216) { ubyte[] buffer=new ubyte[4096]; auto first=true; while(contentLength0) { auto bytesRead=ss.read(buffer); if(first) {writeln(buffer[0..20]); first=false; } f.rawWrite(buffer[0..bytesRead]); contentLength-=bytesRead; } } IIRC there is a blank line after headers in the HTTP protocol, that's how you know you're at the end of the headers i.e. status code/response header [header] blank line body R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: For DLLs, what does export actually do?
On Sun, 10 Feb 2013 12:36:38 -, Ben Davis ent...@cantab.net wrote: On 10/02/2013 08:17, Benjamin Thaut wrote: Am 10.02.2013 03:03, schrieb Ben Davis: My functions are export extern (Windows) - I think they're global...? For example: export extern(Windows) LRESULT DriverProc(DWORD_PTR dwDriverId, HDRVR hdrvr, UINT msg, LONG lParam1, LONG lParam2) nothrow { ... } Do you have a copy of visual studio around? If so you can use dumpbin /EXPORTS your.dll From a visual studio command shell to see the symbols the dll actually exports. Just compare the version where you manually listed them in the exports section with the version where you don't manually list exports. Thanks, that helped expose what's going on. With the def, I get lines like DriverProc = _DriverProc@20. Without it, I get lines like _DriverProc@20 = _DriverProc@20. So the difference is that the export is done under a slightly mangled name if I only mark it in the code, and I need to use the def file to specify the exact name to export by. I suppose this is only necessary for weird things like driver entry points, and not for normal exported functions. A bit more Googling reveals that the @n is the number of bytes taken by arguments, and is part of the stdcall == extern(Windows) convention. So Windows is making me use stdcall and then making me throw that information away in the export table. But hey - it wouldn't be the worst thing I've encountered with the Windows API. (._.' :P) Some more background info: http://en.wikipedia.org/wiki/Name_mangling DllMain is a weird one - it creates all sorts of linker errors if I try it with extern(C) instead of extern(Windows) (which is different from the other methods, which compile fine with extern(C) and then crash at runtime). extern(C) will change the mangling.. so in this case I guess the linker is expecting DllMain but the mangling is incorrect. I wonder if the compiler detects the presence of DllMain and alters the linker line. DMD has a command line option to output the linker command line, maybe see if it changes with/without a DllMain in the code perhaps. Also it doesn't matter what name I export it by or whether I export it at all. I'm getting the feeling this is what was implied by The presence of DllMain() is recognized by the compiler. Good to know anyway - I like to keep stuff clean :) Yep, DllMain isn't a requirement, but if is present should be called by the C runtime when the dll is loaded. You can hook into process start/stop and thread attach/detach with dll main. It's good for thread local storage initialisation - for example. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: Idiomatic way to process const/immutable arrays as ranges
On Mon, 11 Feb 2013 17:13:21 -, Dicebot m.stras...@gmail.com wrote: On Monday, 11 February 2013 at 16:54:04 UTC, Jonathan M Davis wrote: The const(T)[] cannot alter the original array at all, so I concur with Steven in that the complaints about not wanting to use tail-const make no sense. Maybe this article will help clear things up: And I exactly want to prohibit altering original array. What I want is to copy slice (without deep copying of data) and alter this fresh copy. I can't see how it contradicts immutability guarantees or D array design. This *does* prohibit altering the original array (test passed by main below) without deep copying the data, and allows you to alter the fresh copy (arr inside the function). Example: import std.stdio; void foo(const(string)[] arr) { // arr[0] = aa; // Error: arr[0] isn't mutable arr.length = 10; writefln(foo arr.length = %d, arr.length); } void main() { const(string[]) test = [a, b]; // test[0] = aa; // Error: test[0] isn't mutable // test.length = 10; // Error: variable .test cannot modify const foo(test); writefln(test.length = %d, test.length); } What you have to realise is that when you pass an array/slice in D, you get a copy of that array/slice in the function. Just like when you pass an 'int' or any other value type. Think of the array/slice as this struct: struct array { int length; void *ptr; } Passing that to a function would copy the entire struct into the function parameter, altering that parameter would not alter the original. array/slices are the same. The data referred to by 'ptr' is not copied, and neither are the elements of an array/slice. If you did want to alter the original, you'd pass the array/slice by 'ref'erence. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: Why is the 'protected' attribute considered useless?
On Wed, 30 Jan 2013 09:20:54 -, simendsjo simend...@gmail.com wrote: On Wednesday, 30 January 2013 at 03:38:39 UTC, Chad Joan wrote: I've read more than once now that 'protected' is considered useless in D. Why is this? ... * private and protected in D works at module scope, not class scope. You can modify private and protected members from anywhere in the module. I think this is the most common reason ppl think protected is useless, because it has no effect inside the module scope.. but by the same logic private is as useless, so.. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: how can D program find it's own executable name on windows ?
On Tue, 29 Jan 2013 15:51:08 -, rsk82 rs...@live.com wrote: On Tuesday, 29 January 2013 at 15:46:40 UTC, monarch_dodra wrote: stdout.writeln(args[0]); It doesn't work while I have WinMain function that then calls myWinMain, as it is winsamp.d Error: undefined identifier args, did you mean struct CArgs? Try.. 1. Add these lines to the top of winsamp.d (after other includes) import core.sys.windows.windows; import std.utf; string commandLine = null; 2. Add these lines to myWinMain (after variable declarations, before wndclass.style..) wchar[260] moduleName; uint n = GetModuleFileNameW(null, moduleName.ptr, moduleName.length); commandLine = toUTF8(moduleName[0..n]); 3. In WindowProc (I had to add nothrow to my definition BTW) change this line TextOutA(dc, r.right / 2, r.bottom / 2, text.toStringz, text.length); to read: TextOutA(dc, r.right / 2, r.bottom / 2, commandLine.toStringz, commandLine.length); 4. Compile/run it, i.e. dmd -run winsamp.d R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: MS ODBC encoding issue
On Wed, 23 Jan 2013 04:09:01 -, Sam Hu samhudotsa...@gmail.com wrote: for windows console show Chinese character issue,I've solved and posted on the forum before.Please refer to below link: http://forum.dlang.org/thread/suzymdzjeifnfirtb...@dfeed.kimsufi.thecybershadow.net#post-suzymdzjeifnfirtbnrc:40dfeed.kimsufi.thecybershadow.net I tried all that, still doesn't work for me. I suspect I don't have the Chinese Language pack installed, and I don't seem to be able to install it (I have Win 7 Pro here at work). R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: MS ODBC encoding issue
On Wed, 23 Jan 2013 04:41:11 -, Sam Hu samhudotsa...@gmail.com wrote: I've tested and the Chinese character issue really fixed! But I have two more issues here. 1.for connect with DSNless string function provided by my original code as below,I can not make it to connect successfully with really database file.Don't now why yours works. Does the connection function throw? What is the retCode? Note; your connect function throws, and the cleanup happens /after/ that.. which means it doesn't happen at all. You need to use scope(failure) or finally or something like that to ensure cleanup happens. 2.Inserting new record from windows console faile on Chinese characters but success on English characters.If I enter a Chinese character to feed the new record,the program closed (crashed I think) immedialtey and none row affected in the database. #1 First thing to check is that your are reading your input in the correct encoding. Are the characters you are reading from the console encoded as UTF-8, or perhaps in the native OS encoding/codepage. If they're native, and you've stored them in a string then phobos will at some stage attempt to validate/use that string and it will throw (like when you convert it in SQLExecDirectUTF8 for example). What you want is to read the input and ensure it is encoded as UTF-8, so you can pass it around in a string without issues and convert if/when required. To test if it's correct try converting your input string from UTF-8 to UTF-16 and UTF-32 and if it throws, check the exception text for clues. #2 Next thing to check (assuming you've got your input as UTF-8) is that you're passing it to SQL as the correct type in the correct encoding. I see that you are currently using SQLExecDirectW, and converting the entire SQL statement from UTF-8 to UTF-16. Assuming the input was UTF-8, this should probably work (suggesting to me that #1 above is the issue you're currently having). However, if you're sure your input is correctly UTF-8 encoded and it's still not working then another idea to try is to use SQLBindParameter to bind parameters to the statement instead of having their values in the statement itself. For example: hStmt opened int id; - populate from console wchar[] name = toUTF16(inputName); - inputName is from console int i = 1; SQLBindParameter(hStmt, i++, SQL_PARAM_INPUT, SQL_C_SLONG, SQL_INTEGER, 0, 0, id, 0, 0); SQLBindParameter(hStmt, i++, SQL_PARAM_INPUT, SQL_C_WCHAR, SQL_WVARCHAR, colWidth, 0, value.ptr, 0, 0); The statement to execute then becomes insert into artists values(?,?) where each value is replaced by a parameter placeholder '?'. Note, you do not need to enclude strings or dates in '' in the statement, SQL knows the type of the parameter because you're telling it in the bind, so additional '' are not required. Using bind for parameters is a good idea because it makes 2 statements with different parameter values look the same, and this is good because many SQL servers have a statement execution plan cache and for each different statement they need to calculate the execution plan, which takes time, if they find a matching plan and re-use it, it is faster. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: MS ODBC encoding issue
On Mon, 14 Jan 2013 10:02:04 -, Regan Heath re...@netmail.co.nz wrote: I'm more than happy to upload the database file here,but I can't find how to.May I have your mail address?Appreciated for all the help! My email address in the from is valid: regan at netmail dot co dot nz Ok, solved the issue I think. 1. I can connect to your database file with a connection string like.. odbc.connect(rDriver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=PATHGOESHERE\db1.mdb;); Just replace PATHGOESHERE with the real path to the file, using single \ characters for path separators. 2. In fetchAll, I have made the following changes: while(true) { char sz_buf[256]; - wchar[] pszBuf; SQLINTEGER buflen; string[] rowData; - uint uintVal; if(SQLFetch(hStmt)==SQL_NO_DATA) { break; } for(int i=1;i=col;i++) { SQLColAttribute(hStmt, cast(ushort)i, SQL_DESC_NAME, sz_buf.ptr, 256, buf_len, cast(void*)0); SQLColAttribute(hStmt, cast(ushort)i, SQL_DESC_TYPE, cast(void*)0, 0, cast(short*)0, colType); SQLColAttribute(hStmt, cast(ushort)i, SQL_DESC_LENGTH, null, 0, cast(short*)0, colLen); - switch(colType) - { - case SQL_INTEGER: - SQLGetData(hStmt, cast(ushort)i, SQL_C_ULONG, uintVal, uintVal.sizeof, cast(int*)buflen); - rowData ~= to!string(uintVal); - break; - case SQL_VARCHAR: - pszBuf = new wchar[colLen]; - SQLGetData(hStmt, cast(ushort)i, SQL_C_WCHAR, pszBuf.ptr, pszBuf.length, cast(int*)buflen); - pszBuf.length = buflen; - rowData ~= toUTF8(pszBuf); - break; - default: - break; - } } v~=rowData; row++; } The key here is that when we ask for the VARCHAR data, we ask for it as WCHAR (meaning UTF-16 or more likely UCS-2 a subset of UTF-16). We then have to convert it to UTF-8 using std.utf.toUTF8() Your original code was asking for it as SQL_C_CHAR, and the odbc layer knows it cannot represent the Chinese characters in ASCII, so it was returning a '?' for each of them. Now I can see (in Visual-D debugger) the Chinese characters in the rowData, but I can't get it to display correctly on my windows console.. can someone remind me how to do that? R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: MS ODBC encoding issue
I'm more than happy to upload the database file here,but I can't find how to.May I have your mail address?Appreciated for all the help! My email address in the from is valid: regan at netmail dot co dot nz -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: Unicode symbols in the identifiers
On Fri, 11 Jan 2013 02:09:29 -, Andrey andr-...@yandex.ru wrote: Should these variants serve as identifiers? See: http://dlang.org/lex.html#Identifier Identifiers start with a letter, _, or universal alpha, and are followed by any number of letters, _, digits, or universal alphas. Universal alphas are as defined in ISO/IEC 9899:1999(E) Appendix D. (This is the C99 Standard.) Identifiers can be arbitrarily long, and are case sensitive. Identifiers starting with __ (two underscores) are reserved. Regan -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: MS ODBC encoding issue
On Mon, 24 Dec 2012 07:18:51 -, Sam Hu samhudotsa...@gmail.com wrote: On Friday, 21 December 2012 at 15:20:39 UTC, Regan Heath wrote: On Wed, 19 Dec 2012 06:33:16 -, Sam Hu samhudotsa...@gmail.com wrote: On Monday, 10 December 2012 at 14:43:08 UTC, Regan Heath wrote: Ahh, of course. Now I'm having linking issues :p I'm using VisualD and I've added odbc32.lib to the right place, but some symbols are still missing - specifically the W versions. I've dumped the symbols in the DMC odbc32.lib and it's missing those symbols. R I have such extra lib files to link successfully but I don't find any way to upload here.Sorry. NP, I am up and running. I can run the test app and see my existing rows, plus insert new ones. I got it working with a connection string directly to an access database file on disk without needing a DSN, not sure why you were having trouble with that. So, what sort of data do I need to add, which will cause the issues you were originally having :) R Really excited to hear that! As I said,field contains Chinese characters will produce error during read from and write back to database file; Can you save some of these characters in a text file, as UTF-8, and zip that and upload/attach it here for me to try. I want to make sure I'm testing the exact same data as you are. I suspect the issue you're having is related to the encoding of the strings. D expects/uses UTF-8, but the database will be configured with a specific locale/encoding for the columns in question. So, can you export/describe your database table to me, columns, and locales/encodings etc so I can compare them to mine. and can't work out a DSNless connection function. Would be much appreciated if you would like to share your complete code here. At present I'm simply using your code, with only very minor changes to the odbcutiltest.d file, like the connection string for example: odbc.connect(rDriver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=C:\Development\D\src\odbcutiltest\test.accdb;); And the table name artists (IIRC) plus I have 3 columns, so.. write(Please enter artist ID:); string id=chomp(readln); write(Please enter artist Name:); string name=chomp(readln); write(Please enter artist Age:); string age=chomp(readln); string sql=insert into artists values(~id~,'~name~',~age~);; int changed=odbc.executeNonQuery(sql); writefln(%d row affected.,changed); R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: calling fgets()
On Mon, 24 Dec 2012 12:00:05 -, Red resm...@lavabit.com wrote: On Sunday, 23 December 2012 at 16:20:47 UTC, Mike Wey wrote: If you declare an char array you could pass it's pointer and length as the first two arguments. char[] buff = new char[1024]; fgets(buff.ptr, buff.length, someStream); buff = buff[0 .. strlen(buff)]; Thanks, that does work (buff.length has to be cast to an int). Which is surprising. I would have thought that a char[] in D would not equate to a char array in C since the D char's are UTF-8, and that a byte[] would have to be used (byte[] also works with a cast). Technically you're more or less correct :) But, if your input is all ASCII then as ASCII is a subset of UTF-8 it just works. If however your input is not ASCII, but say Chinese characters in a different encoding/locale then it will go bang! at some point, probably when you try to write it back to the screen or foreach over it. Using ubyte[] is the technically correct method IMO. Then in a perfect world you'd call a method to convert that ubyte[] from it's known (has to be known or detectable somehow) encoding into UTF-8 for use in your D code. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: MS ODBC encoding issue
On Wed, 19 Dec 2012 06:33:16 -, Sam Hu samhudotsa...@gmail.com wrote: On Monday, 10 December 2012 at 14:43:08 UTC, Regan Heath wrote: Ahh, of course. Now I'm having linking issues :p I'm using VisualD and I've added odbc32.lib to the right place, but some symbols are still missing - specifically the W versions. I've dumped the symbols in the DMC odbc32.lib and it's missing those symbols. R I have such extra lib files to link successfully but I don't find any way to upload here.Sorry. NP, I am up and running. I can run the test app and see my existing rows, plus insert new ones. I got it working with a connection string directly to an access database file on disk without needing a DSN, not sure why you were having trouble with that. So, what sort of data do I need to add, which will cause the issues you were originally having :) R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: MS ODBC encoding issue
On Fri, 07 Dec 2012 00:27:57 -, Sam Hu samhudotsa...@gmail.com wrote: On Thursday, 6 December 2012 at 16:44:01 UTC, Regan Heath wrote: On Thu, 06 Dec 2012 01:26:32 -, Sam Hu samhudotsa...@gmail.com wrote: Known issues: Under console reading Access table recordsets works fine ,inserting a new record which contains only English characters works fine as well,but inserting new record which contains Chinese character will crash; If calling the fetchAll in a DFL gui form and try to display the result value in a Text control,English values works fine but the Text control will display nothing when any record (row/field) contains Chinese character. Where do the win32.sql etc modules come from? R You can find it from below links: http://www.dsource.org/projects/bindings/wiki/WindowsApi https://github.com/AndrejMitrovic/WindowsAPI Ahh, of course. Now I'm having linking issues :p I'm using VisualD and I've added odbc32.lib to the right place, but some symbols are still missing - specifically the W versions. I've dumped the symbols in the DMC odbc32.lib and it's missing those symbols. I am guessing I should be using converted M$ libs and I'll do this next, when I get a spare moment (work has been busy lately). R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: MS ODBC encoding issue
On Thu, 06 Dec 2012 01:26:32 -, Sam Hu samhudotsa...@gmail.com wrote: Known issues: Under console reading Access table recordsets works fine ,inserting a new record which contains only English characters works fine as well,but inserting new record which contains Chinese character will crash; If calling the fetchAll in a DFL gui form and try to display the result value in a Text control,English values works fine but the Text control will display nothing when any record (row/field) contains Chinese character. Where do the win32.sql etc modules come from? R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: MS ODBC encoding issue
On Wed, 05 Dec 2012 03:29:50 -, Sam Hu samhudotsa...@gmail.com wrote: On Tuesday, 4 December 2012 at 10:05:16 UTC, Nathan M. Swan wrote: I've never used ODBC before, but a quick scan of the MSDN docs suggests that you should use SQL_C_WCHAR instead, maybe using some D wstring functions too. BTW, convert sql.ptr - std.string.toStringz(sql); this is good practice, though I'm not sure it's your problem. NMS Appreciated the prompt help!Unfortunately I've not fixed the issue yet.Changing to SQL_C_WCHAR and contained the result value by wchar* does not help much. If you make a complete working (but for the problem) code sample available I'll download it and try it here. I have some experience with ODBC and a working example in C/C++ to compare things with so I should be able to track it down. No promises tho, I am supposed to be working :p R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: VisualD solution configuration
On Sun, 02 Dec 2012 15:08:51 -, Zhenya zh...@list.ru wrote: On Sunday, 2 December 2012 at 15:03:26 UTC, Zhenya wrote: On Sunday, 2 December 2012 at 14:58:24 UTC, Zhenya wrote: On Sunday, 2 December 2012 at 14:52:24 UTC, Lubos Pintes wrote: Not sure if I understand what you ask here, but you probably need to add all files you want to compile to the project. Thus not only the main.d, but all modules. Dňa 2. 12. 2012 11:56 Zhenya wrote / napísal(a): Hi! I'm sorry,maybe it is a little bit stupid question,but how to configure VisualD project to get it compile not only main.d but all files in project? I added 2 modules in project.But compiled only one. I have the following errors: Error 42: Symbol Undefined _D10dispatcher7__arrayZ Debug\space.obj(space) Error 42: Symbol Undefined _D10dispatcher12__ModuleInfoZ I added line module dispatcher; in file dispatcher.d and all compiled. Strange,I thought module name inferred from filename. What folder was main.d in, and what folder was dispatcher.d in? R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: template ref parameter
On Wed, 21 Nov 2012 12:02:45 -, Jack Applegame jappleg...@gmail.com wrote: void foo(ref int a) { a--; } struct functor(A...) { void function(A) functor; } functor!int f;// functor!(ref int) - wrong f.functor = foo; // Error: cannot implicitly convert expression ( foo) of type void function(ref int a) to void function(int) Hmm.. well I got past your initial problem, but I have a new one.. alias void function(ref int) funcType; void foo(ref int a) { a--; } struct functor(A...) { A func; } void main() { functor!funcType f; f.func = foo; //Error: f.func is not an lvalue } -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: template ref parameter
On Wed, 21 Nov 2012 12:30:08 -, Regan Heath re...@netmail.co.nz wrote: On Wed, 21 Nov 2012 12:02:45 -, Jack Applegame jappleg...@gmail.com wrote: void foo(ref int a) { a--; } struct functor(A...) { void function(A) functor; } functor!int f;// functor!(ref int) - wrong f.functor = foo; // Error: cannot implicitly convert expression ( foo) of type void function(ref int a) to void function(int) Hmm.. well I got past your initial problem, but I have a new one.. alias void function(ref int) funcType; void foo(ref int a) { a--; } struct functor(A...) { A func; } void main() { functor!funcType f; f.func = foo; //Error: f.func is not an lvalue } Just realised what is happening here. f.func = is trying to call the function, and assign foo to the void result. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: template ref parameter
On Wed, 21 Nov 2012 12:32:24 -, Regan Heath re...@netmail.co.nz wrote: On Wed, 21 Nov 2012 12:30:08 -, Regan Heath re...@netmail.co.nz wrote: On Wed, 21 Nov 2012 12:02:45 -, Jack Applegame jappleg...@gmail.com wrote: void foo(ref int a) { a--; } struct functor(A...) { void function(A) functor; } functor!int f;// functor!(ref int) - wrong f.functor = foo; // Error: cannot implicitly convert expression ( foo) of type void function(ref int a) to void function(int) Hmm.. well I got past your initial problem, but I have a new one.. alias void function(ref int) funcType; void foo(ref int a) { a--; } struct functor(A...) { A func; } void main() { functor!funcType f; f.func = foo; //Error: f.func is not an lvalue } Just realised what is happening here. f.func = is trying to call the function, and assign foo to the void result. Or not, duh! A... grr. alias void function(ref int) funcType; void foo(ref int a) { a--; } struct functor(A...) { A[0] func; } void main() { functor!funcType f; f.func = foo; } R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: About demangling
On Thu, 01 Nov 2012 15:40:23 -, H. S. Teoh hst...@quickfur.ath.cx wrote: On Thu, Nov 01, 2012 at 03:16:25PM +0100, Dan wrote: On Thursday, 11 October 2012 at 21:04:28 UTC, Alex Rønne Petersen wrote: On 11-10-2012 22:56, Sean Kelly wrote: On Oct 11, 2012, at 6:17 AM, Lubos Pintes lubos.pin...@gmail.com wrote: Hi, Can someone point me to some source with information about name demangling when compiling some D program and the famous linker error 42 appears? Filter the symbol names through core.demangle. We even have a tool for that: https://github.com/D-Programming-Language/tools/blob/master/ddemangle.d Does this work and if so how? I've seen a thread about the demangling tool not working on types, just functions. The comment at top of this file says Replaces *all* occurrences of mangled D symbols in the input... so I assume it deals with types? The help says: 'If inputfile is a single dash '-', standard input is read.' [...] This program only calls the library core.demangle. So if core.demangle doesn't demangle something, then it won't get demangled. The problem is, there's a comment in core.demangle that seems to say that some mangled symbols are skipped because they are not pertinent to the ABI, or something to that effect. Meaning that *not* all symbols are getting demangled. I think this should be an enhancement request in the bugtracker. There is also a bug in demangle.d, line 55: foreach (line; stdin.byLine()) should read: foreach (line; f.byLine()) R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: About demangling
On Thu, 01 Nov 2012 15:40:23 -, H. S. Teoh hst...@quickfur.ath.cx wrote: On Thu, Nov 01, 2012 at 03:16:25PM +0100, Dan wrote: On Thursday, 11 October 2012 at 21:04:28 UTC, Alex Rønne Petersen wrote: On 11-10-2012 22:56, Sean Kelly wrote: On Oct 11, 2012, at 6:17 AM, Lubos Pintes lubos.pin...@gmail.com wrote: Hi, Can someone point me to some source with information about name demangling when compiling some D program and the famous linker error 42 appears? Filter the symbol names through core.demangle. We even have a tool for that: https://github.com/D-Programming-Language/tools/blob/master/ddemangle.d Does this work and if so how? I've seen a thread about the demangling tool not working on types, just functions. The comment at top of this file says Replaces *all* occurrences of mangled D symbols in the input... so I assume it deals with types? The help says: 'If inputfile is a single dash '-', standard input is read.' [...] This program only calls the library core.demangle. So if core.demangle doesn't demangle something, then it won't get demangled. The problem is, there's a comment in core.demangle that seems to say that some mangled symbols are skipped because they are not pertinent to the ABI, or something to that effect. Meaning that *not* all symbols are getting demangled. I think this should be an enhancement request in the bugtracker. Also, running this: dmd test.d | demangle.exe - on windows, results in this: invalid UTF-8 sequence Usage: demangle.exe [options] inputfile Demangles all occurrences of mangled D symbols in the input and writes to standard output. If inputfile is a single dash '-', standard input is read. Options: --help, -hShow this help Adding writefln to demangle.d to debug the issue shows that args[1] is - and that getopt is throwing the exception invalid UTF-8 sequence. Omitting the - works, and demangle reads stdin. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: About demangling
On Thu, 01 Nov 2012 16:25:56 -, Regan Heath re...@netmail.co.nz wrote: Adding writefln to demangle.d to debug the issue shows that args[1] is - and that getopt is throwing the exception invalid UTF-8 sequence. I was wrong here, this line is the issue: stderr.writeln(e.msg); For some reason, when run from command prompt and passed - as an arg it errors. If I run it in debug mode in VisualD it works and outputs: Unrecognized option - R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: About demangling
On Thu, 01 Nov 2012 17:21:29 -, H. S. Teoh hst...@quickfur.ath.cx wrote: On Thu, Nov 01, 2012 at 04:25:56PM -, Regan Heath wrote: On Thu, 01 Nov 2012 15:40:23 -, H. S. Teoh hst...@quickfur.ath.cx wrote: On Thu, Nov 01, 2012 at 03:16:25PM +0100, Dan wrote: On Thursday, 11 October 2012 at 21:04:28 UTC, Alex Rønne Petersen wrote: On 11-10-2012 22:56, Sean Kelly wrote: [...] We even have a tool for that: https://github.com/D-Programming-Language/tools/blob/master/ddemangle.d [...] Also, running this: dmd test.d | demangle.exe - on windows, results in this: invalid UTF-8 sequence [...] Omitting the - works, and demangle reads stdin. [...] https://github.com/D-Programming-Language/tools/pull/35 Perfect, thanks. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: getters and setters not an lvalue
On Wed, 31 Oct 2012 14:08:18 -, maarten van damme maartenvd1...@gmail.com wrote: Ok, looking forward to the fix :) Btw, I have a foreach loop and in that foreach loop I want to decide if the current element can stay and if not, I want to remove it. If removing it yields an empty range in the foreach loop, it crashes. What's the sane way to do this? Altering the thing you're foreaching over is generally frowned upon because it causes issues like this. Ideally D would const-ify the thing you're foreaching inside the body of the foreach to prevent it. Usually you end up using for and an index value instead. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: Correct way to map C #define to version
On Mon, 29 Oct 2012 11:31:33 -, Sumit Raja sumitr...@gmail.com wrote: Thanks both this works great for structs. Anything similar I can do for enums? Example? (The C/C++ code you're trying to convert..) R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: Correct way to map C #define to version
On Mon, 29 Oct 2012 13:47:46 -, Sumit Raja sumitr...@gmail.com wrote: On Monday, 29 October 2012 at 12:31:56 UTC, Regan Heath wrote: On Mon, 29 Oct 2012 11:31:33 -, Sumit Raja sumitr...@gmail.com wrote: Thanks both this works great for structs. Anything similar I can do for enums? Example? (The C/C++ code you're trying to convert..) Yeah that might help... One example here (though it seems slightly inconsistent as the enum following the second if seems to be padded for the values inside the ifdef): enum PixelFormat { PIX_FMT_NONE= -1, . . . #ifdef AV_PIX_FMT_ABI_GIT_MASTER PIX_FMT_RGBA64BE, /// packed RGBA 16:16:16:16, 64bpp, 16R, 16G, 16B, 16A, the 2-byte value for each R/G/B/A component is stored as big-endian PIX_FMT_RGBA64LE, /// packed RGBA 16:16:16:16, 64bpp, 16R, 16G, 16B, 16A, the 2-byte value for each R/G/B/A component is stored as little-endian PIX_FMT_BGRA64BE, /// packed RGBA 16:16:16:16, 64bpp, 16B, 16G, 16R, 16A, the 2-byte value for each R/G/B/A component is stored as big-endian PIX_FMT_BGRA64LE, /// packed RGBA 16:16:16:16, 64bpp, 16B, 16G, 16R, 16A, the 2-byte value for each R/G/B/A component is stored as little-endian #endif PIX_FMT_GBRP, /// planar GBR 4:4:4 24bpp . . . PIX_FMT_GBRP16LE, /// planar GBR 4:4:4 48bpp, little endian #ifndef AV_PIX_FMT_ABI_GIT_MASTER PIX_FMT_RGBA64BE=0x123, /// packed RGBA 16:16:16:16, 64bpp, 16R, 16G, 16B, 16A, the 2-byte value for each R/G/B/A component is stored as big-endian PIX_FMT_RGBA64LE, /// packed RGBA 16:16:16:16, 64bpp, 16R, 16G, 16B, 16A, the 2-byte value for each R/G/B/A component is stored as little-endian PIX_FMT_BGRA64BE, /// packed RGBA 16:16:16:16, 64bpp, 16B, 16G, 16R, 16A, the 2-byte value for each R/G/B/A component is stored as big-endian PIX_FMT_BGRA64LE, /// packed RGBA 16:16:16:16, 64bpp, 16B, 16G, 16R, 16A, the 2-byte value for each R/G/B/A component is stored as little-endian #endif PIX_FMT_0RGB=0x123+4, /// packed RGB 8:8:8, 32bpp, 0RGB0RGB... . . . }; Well, I can't see a way to do that in D without duplicating most of the enum. :( If no-one else can think of a way, I reckon we want an enhancement request to allow version or static if or perhaps mixin inside enums... http://d.puremagic.com/issues/ R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: Sort order of dirEntries
On Thu, 25 Oct 2012 01:15:06 +0100, Joseph Rushton Wakeling joseph.wakel...@webdrake.net wrote: Hello all, I've just been playing with dirEntries and by the looks of it, it returns these entries in arbitrary order. On windows, assuming it was using FindFirstFile or similar you would get alphabetical order on some platforms/file systems and FAT table order on others. I imagine linux and associated platforms have similar behaviour. Is there a way to get it to sort the entries in alphabetical order, other than the obvious one of storing them in an array and sorting that? (This is untenable because I'm talking about a lot of files...:-) To get a sorted list someone has to load all the entries and sort them. I doubt the file system is going to do it, so either the library routine would have to, or you're going to have to. As most file systems and libraries should take the most efficient approach first and foremost it's likely you're going to have to do it yourself. :) R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: How to start new command with arguments, pass data to its stdin read its output?
On Tue, 23 Oct 2012 13:29:59 +0100, denizzzka 4deni...@gmail.com wrote: On Tuesday, 23 October 2012 at 12:19:08 UTC, Adam D. Ruppe wrote: On Tuesday, 23 October 2012 at 11:34:35 UTC, denizzzka wrote: Something like execv() but with stdin/stdout? If you're on linux i have a little file that might help: http://arsdnet.net/dcode/exec.d int exec( string program, string[] args = null, string input = null, string* output = null, string* error = null, string[] environment = null); Thanks! It is suitable for my case. I think something like this should be in the standard library. Coming soon I believe. The new std.process should support it. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: Correct way to map C #define to version
On Mon, 22 Oct 2012 12:39:48 +0100, bearophile bearophileh...@lycos.com wrote: Sumit Raja: Am I using version correctly? How is this done usually? I think version is usually meant to be given as compiler switch. Maybe a simple enum + static if is enough in your case. Good suggestion. I was curious so I had a tinker and produced this example which might be useful to you. import core.stdc.stdint; import std.stdio; enum LIBAVFILTER_VERSION_MAJOR = 2; \\ change this to 3 to see a difference in size below enum LIBAVFILTER_VERSION_MINOR = 77; enum LIBAVFILTER_VERSION_MICRO = 100; enum FF_API_PACKING = (LIBAVFILTER_VERSION_MAJOR 3); struct AVFilterBufferRefAudioProps { uint64_t channel_layout;/// channel layout of audio buffer int nb_samples; /// number of audio samples per channel int sample_rate;/// audio buffer sample rate static if(FF_API_PACKING) { int planar; /// audio buffer - planar or packed } } void main() { writefln(size of AVFilterBufferRefAudioProps = %s, AVFilterBufferRefAudioProps.sizeof); } R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: optlink and weak symbols
On Thu, 18 Oct 2012 07:41:16 +0100, Jacob Carlborg d...@me.com wrote: On 2012-10-18 05:12, Ellery Newcomer wrote: nice tip, but adding extern doesn't change link behavior at all. Hmm, are you linking with the DLL (the import library) ? In not, you need to use dlopen, or what the corresponding Windows function is. LoadLibrary[Ex] R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: Stack trace output on windows
On Tue, 16 Oct 2012 17:52:38 +0100, Benjamin Thaut c...@benjamin-thaut.de wrote: Am 16.10.2012 18:38, schrieb Regan Heath: I have some C/C++ code which handles windows SEH exceptions and can output (in debug mode) a stack trace, for example: But, it doesn't output symbol names for the D functions. Does anyone know why not? Is there some reason it cannot? Perhaps the debug information in the binary is incomplete.. IIRC that was an issue in the past and may still be. I managed to wind my way through the code and find the stacktrace.d module with the StackTrace class which appears to be producing the stack trace. Comparing it to my own, the major difference is on the StackWalk call I pass FunctionTableAccessRoutine and GetModuleBaseRoutine routines (3rd and 2nd to last parameters) .. I'm guessing there is some reason this wont work in D, can anyone enlighten me? R You could use cv2pdb to convert the debugging symbols into the pdb format, then the stackwaler will always be able to resolve the stack. So, the problem in my case is that dbghelp.dll doesn't understand the DMD CodeView (CV) debug information? Ahh.. I think I've figured out where I've been going wrong. It's been a while since I worked with any D and I was not passing the -g or -gc compile flags, only -debug, duh! I figured this out when cv2pdb complained .. no codeview debug entries found But, now I cannot compile.. (DMD32 D Compiler v2.060) C:\dmd -g -debug crash.d OPTLINK (R) for Win32 Release 8.00.12 Copyright (C) Digital Mars 1989-2010 All rights reserved. http://www.digitalmars.com/ctg/optlink.html OPTLINK : Error 118: Filename Expected Path=..etc.. Adding -v shows a linker command of: C:\Development\D\dmd2\windows\bin\link.exe crash,,nul,user32+kernel32/co/noi; The input file crash.obj is present, and a quick test removing the /co (debug information) C:\Development\D\dmd2\windows\bin\link.exe crash,,nul,user32+kernel32/co/noi; works fine.. any ideas where this is going wrong? Depending on your version of the dbghelp.dll, which comes with the windows sdk, or visual studio, it will also correctlry resolve cv smybols. I have windows 7 64 bit service pack 1 with visual studio 2010 installed and the D stacktracking correctly resolves cv symbols for me. Interesting. I searched and found 13 different versions of dbghelp.dll installed on my system. I have windows 7 64 bit SP1 with VS2010 installed and it's not working for me. I suspect in my case it's using one of the other 12 dlls. In my VS2010 folder(s) I found 3 dbghelp.dll's all version 6.12.2.633, does that match yours? In c:\Windows\System32 SysWOW64 and the winsxs folders the version is 6.1.7601.17514, which looks older but has a newer date on it. I also found version 6.1.7600.16385 in the winsxs folders. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: abnormal program termination
On Wed, 29 Aug 2012 18:43:27 +0100, Ellery Newcomer ellery-newco...@utulsa.edu wrote: On 08/28/2012 01:03 PM, Ellery Newcomer wrote: On 08/28/2012 09:55 AM, Regan Heath wrote: I searched the DMD sources, just in case the message abnormal program termination was DMD specific, and I found nothing. Then I searched all files and the string appears in the dmd.exe binary, making me suspect the compiler used to produce dmd.exe put it there, so perhaps there is a dmc option to disable it. maybe so found it. Where did you find that.. I still can't find the blasted thing :p void dmd_51d770(char* msg, char* title) { HANDLE handle; DWORD nchars; handle = GetStdHandle(STD_ERROR_HANDLE); if(handle == INVALID_HANDLE_VALUE || WriteConsoleA(handle, msg, strlen(msg), nchars, 0) == 0) { MessageBoxA(NULL, msg, title, MB_OK|MB_ICONHAND|MB_TASKMODAL); } } good old olly. Sorry to waste your time. NP. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: abnormal program termination
On Tue, 28 Aug 2012 21:03:47 +0100, Ellery Newcomer ellery-newco...@utulsa.edu wrote: If you like, you could try building the unreduced case download pyd https://bitbucket.org/ariovistus/pyd from top dir, run (python setup.py install) go to examples/wrap, run (python setup.py build) Ok. I downloaded and installed python. Then pyd. I run python setup.py build in examples\wrap and see the ICE. I run python setup.py build 1a.txt 21 and get a popup box :) So, we're on the same page at least.. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: abnormal program termination
On Wed, 29 Aug 2012 09:47:57 +0100, Regan Heath re...@netmail.co.nz wrote: On Tue, 28 Aug 2012 21:03:47 +0100, Ellery Newcomer ellery-newco...@utulsa.edu wrote: If you like, you could try building the unreduced case download pyd https://bitbucket.org/ariovistus/pyd from top dir, run (python setup.py install) go to examples/wrap, run (python setup.py build) Ok. I downloaded and installed python. Then pyd. I run python setup.py build in examples\wrap and see the ICE. I run python setup.py build 1a.txt 21 and get a popup box :) So, we're on the same page at least.. How do I get/see the full dmd.exe command line being executed? (I have never used python.. so go slow) R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: abnormal program termination
On Sat, 25 Aug 2012 01:10:05 +0100, Ellery Newcomer ellery-newco...@utulsa.edu wrote: I am running into an ICE on windows - Assertion Failure on such-and-such line in mtype.c - and I am trying to get a test command for to reduce it with the redoubtable dustmite. Normally, 'abnormal program termination' is printed to the console; however if I try to redirect stderr for greppage purposes, windows presents me with a message box with the same message. Any ideas how to disable this abomination? Can you show us an example of how you're redirecting stderr.. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: abnormal program termination
On Tue, 28 Aug 2012 15:59:34 +0100, Ellery Newcomer ellery-newco...@utulsa.edu wrote: On 08/28/2012 06:37 AM, Regan Heath wrote: On Sat, 25 Aug 2012 01:10:05 +0100, Ellery Newcomer ellery-newco...@utulsa.edu wrote: I am running into an ICE on windows - Assertion Failure on such-and-such line in mtype.c - and I am trying to get a test command for to reduce it with the redoubtable dustmite. Normally, 'abnormal program termination' is printed to the console; however if I try to redirect stderr for greppage purposes, windows presents me with a message box with the same message. Any ideas how to disable this abomination? Can you show us an example of how you're redirecting stderr.. R dmd stuff 21 I searched the DMD sources, just in case the message abnormal program termination was DMD specific, and I found nothing. Then I searched all files and the string appears in the dmd.exe binary, making me suspect the compiler used to produce dmd.exe put it there, so perhaps there is a dmc option to disable it. If that's not it.. What Windows are you on? Do you have visual studio or another JIT debugger installed? I am on Windows 7 x64 and I have been playing with a test.exe (built in VS in debug mode). I can't get my version of windows to output abnormal program termination no matter what I tried to make my application do assert, throw exception, divide by zero, illegal pointer/memory write, etc. If I do an assert(0) I see: ...test Assertion failed: 0, file ...\test.cpp, line 27 plus a popup window saying: Microsoft Visual C++ Debug Library Debug Error! Program: ... This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information. (Press Retry to debug the application) I suspect the popup is a hook into the JIT debugger I have installed (visual studio). By default some versions of windows use DrWatson (drwtsn32.exe), later versions use something else. Google found me this tho, might be helpful: http://blogs.msdn.com/b/alejacma/archive/2011/02/18/how-to-disable-the-pop-up-that-windows-shows-when-an-app-crashes.aspx R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: stdlib.exit()
On Mon, 20 Aug 2012 21:03:25 +0100, David d...@dav1d.de wrote: You could define a custom ExitException and throw that, catching it at the top level and returning the error code stored inside it, from main(). Not ideal, but it would work. Thi is really not ideal Didn't I just say that.. :p Not ideal, but it would work. - Regan Heath , since this is for a argument-parser, --help should print the help and then exit. Still, it can be done.. int main(string[] args) { int retval = 0; try { ParseArguments(args); } catch(ExitException e) { // Silent retval = e.retval; } catch(Exception e) { writefln(Error: %s, e...); retval = 1; } return retval; } void ParseArguments(string[] args) { .. parse .. calls CmdHelp(); } void CmdHelp() { writeln(...); throw ExitException(0); } R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: stdlib.exit()
On Mon, 20 Aug 2012 10:03:56 +0100, David d...@dav1d.de wrote: Am 20.08.2012 09:15, schrieb Tracey: I use the following: import std.c.stdlib; exit(0); Yeah, but that doesn't terminate the runtime and will not call any dtors, right? std.c.stdlib.exit is the C runtime exit function which doesn't know anything about D's runtime, which is layered on top. So, I would not expect any D runtime cleanup to occur. You could define a custom ExitException and throw that, catching it at the top level and returning the error code stored inside it, from main(). Not ideal, but it would work. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: Cannot build ws2_32.lib
On Fri, 03 Aug 2012 07:00:25 +0100, Andre Tampubolon an...@lc.vlsm.org wrote: On 8/3/2012 12:31 AM, Regan Heath wrote: Have you downloaded and extracted a normal dmd 2.0 installation/zip? If so, you should have: some path\dmd2\windows\lib\ws2_32.lib and your some path\dmd2\windows\bin\sc.ini Actually I just solved the problem, by copying all the libs from dmd.2.0.59.zip into C:\dm\lib\ That's odd. I don't have ws2_32.lib in my dmc\dm\lib folder at all. And this is my sc.ini: [Environment] LIB=C:\dmd\lib DFLAGS=-IC:\dmd\import -IC:\dmd\phobos LINKCMD=link.exe So, your sc.ini isn't pointing at dm\lib.. why would copying files there make it work? My sc.ini has: [Environment] LIB=%@P%\..\lib;\dm\lib DFLAGS=-I%@P%\..\..\src\phobos -I%@P%\..\..\src\druntime\import LINKCMD=%@P%\link.exe %@P% resolves to the \dmd2\windows\bin folder so my LIB statement points first at dmd2\windows\lib which is where ws2_32.lib is. I wonder.. Is dm\bin in your path? If so link.exe in your case is probably dm\bin\link.exe and the sc.ini there has: LIB=%@P%\..\lib;%@P%\..\mfc\lib;%LIB% which points to dm\lib. If I were you, and you're not using dmc directly, I would remove dm\bin from the path and put dmd2\windows\bin there instead, then you should see the same behaviour as me. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: Cannot build ws2_32.lib
On Thu, 02 Aug 2012 16:59:32 +0100, Andre Tampubolon an...@lc.vlsm.org wrote: I found this code from this page: http://rosettacode.org/wiki/Category:D import std.stdio, std.socket; void main(){ writefln(%s, Socket.hostName()); } When I tried to build it (I'm on Windows, anyway), I got this: C:\Users\CSL-NB-064\Codes\Ddmd hostname.d OPTLINK (R) for Win32 Release 8.00.5 Copyright (C) Digital Mars 1989-2009 All rights reserved. http://www.digitalmars.com/ctg/optlink.html ws2_32.lib Warning 2: File Not Found ws2_32.lib C:\dmd\lib\phobos.lib(socket) Error 42: Symbol Undefined _WSAIoctl@36 --- errorlevel 1 Works for me :P Have you downloaded and extracted a normal dmd 2.0 installation/zip? If so, you should have: some path\dmd2\windows\lib\ws2_32.lib and your some path\dmd2\windows\bin\sc.ini should have something like: LIB=%@P%\..\lib;\dm\lib which will point dmd at that ws2_32.lib file. If you have those libs, and sc.ini, then perhaps all you're missing is the correct PATH setting, I have some path\dmd2\windows\bin in my PATH. If that doesn't help, or you already have it, I'd start by getting a normal installation/zip and see if it works, if so then replace the files you're (re-)building and try again - it should also work. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: Raw socket using data transfer
On Wed, 01 Aug 2012 11:00:54 +0100, Gangadhar gangadhar@gmail.com wrote: By using raw s ocket programing data transfer from client to server please help me about this,any one have source code send me . The phobos source contains socket code you can inspect .. perhaps not RAW sockets but I suspect you mean low-level STREAM or UDP and not actually RAW sockets (correct me if I'm wrong). Otherwise, there is always google. You do sockets programming in D, exactly as you would in C/C++ all you need is a .d file describing the C socket API (structures, and function signatures) and then you compile and link to ws2_32.lib (on windows). R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: Detector for unused variables
On Wed, 01 Aug 2012 11:38:46 +0100, bearophile bearophileh...@lycos.com wrote: Regan Heath: Indeed. IIRC Walter's rationale on things like this has always been that they belong in 3rd party tools. Walter is not always right. Well, in this case I agree with him. You're not looking at the big picture. If you make detecting un-used variables a /requirement/ for implementing a D compiler, you make it that much less likely someone will write one, which raises the bar for D's adoption. The reason why there are so few good C++ compilers is that the language is too hard to implement, we don't want D to go that way. It's why the DMD front end is available for use, so people can create tools like this, syntax highlighters, re-formatters, dependency tree diagrams, or... you name it. Detecting unused variables is a core feature, it belongs in the compiler Says you. I disagree. We may have gotten used to it being there, but it's not part of the compilation phase but rather part of the development phase and/or the quality control phase which are arguably the realm of the IDE or a lint checker. like compile-time array bound tests and other errors currently detected by DMD. The key word used here is error. Unused variables do not affect the compilation of a program, they're simply ignored and have no effect. Array bounds errors will crash the program. This allows everyone to use it with minimum work, so everyone enjoys it, and it requires less work to be implemented because the compiler already does lot of analysis. Sure, but everyone is not the bottleneck, Walter is. The work to implement it has to be done by someone, somewhere. If we make it a requirement for a D compiler then every D compiler writer has to do it, including Walter and as a result all D compilers will be that much worse for the wasted time/energy used to implement it, not to mention fix any bugs that arise - as they will be very visible - despite being almost irrelevant to the main purpose of the compiler. If it's done by a 3rd party tool it will be done better - as more time can be spent on it, as it's a main feature of said tool, etc. In short, it's better for everyone if it's done in a 3rd party tool. Further, that tool could be fully integrated, i.e. distributed by/with the compiler and run as a pre or post compile step automatically such that to users it's indistinguishable whether the compiler or the tool is doing the work. All we need is someone to produce and maintain the tool, and for Walter to add it to the distribution and hook it into the compiler. Then, we can have competing tools, and competition breeds improvement.. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: Detector for unused variables
On Wed, 01 Aug 2012 12:03:01 +0100, Andre Tampubolon an...@lc.vlsm.org wrote: The Go compiler is able to detect unused variables, and strangely they are regarded as an error. It's not really a question of able to, or not. I'm sure were Walter to decide to add this feature to D he would also be able to. It also doesn't matter what another language choses to do. Why you'd want an unused variable to be an error is beyond me - it has absolutely no effect on the resulting executable, if it did it would be a bug. What matters, ultimately, from a user point of view is whether the feature exists or not. We can solve that by having a 3rd party tool bundled with the compiler and this would be the best solution for all the reasons outlined earlier. R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: Detector for unused variables
On Wed, 01 Aug 2012 15:52:22 +0100, bearophile bearophileh...@lycos.com wrote: Regan Heath: If you make detecting un-used variables a /requirement/ for implementing a D compiler, you make it that much less likely someone will write one, Detecting unused variables can be written as a part of the front-end. Or it can be written using the front-end. It's meant to be shared by LDC and GDC that use the same front-end. Why? We may have gotten used to it being there, but it's not part of the compilation phase but rather part of the development phase and/or the quality control phase which are arguably the realm of the IDE or a lint checker. In theory you are right, in practice I don't know how much this idea is applicable to D/DMD and how much good it does. In Clang they have added a switch to perform extra static tests on the code. It's a feature built in the compiler. I think this is an acceptable place to put an unused variable warning in DMD. You're missing my main point which is that you can get the appearance of a compiler feature with a 3rd party tool bundled with the compiler, the difference/benefits of a 3rd party tool are: 1. The feature it implements is not a requirement for all D compilers. 2. Walter doesn't have to implement it. And more minor points include: 3. We can have competition between 3rd party vendors. 4. People can select/run their favorite tool. 5. A crashing tool/feature will no stop compilation. Basically, having a 3rd party tool will look exactly like a feature of the compiler, but it will be better for the reasons above. R
Re: Writing very large files 50+ GB
On Fri, 27 Jul 2012 02:50:56 +0100, wmunger wmun...@gmail.com wrote: I need to write to a file that is 50 to 250GB on all three major operating systems. I tried to use the c function pwrite64. But it is not available on the Mac. I have seen where some have used the iostream in C++ but this does not seem to work on the Mac. Is there any way to write in D very large files. After all I would rather write in D than wrap C or C++ code. Have you looked for open, lseek(64) and write? R -- Using Opera's revolutionary email client: http://www.opera.com/mail/
Re: More WinAPI problems
On Fri, 20 Jul 2012 14:07:51 +0100, DLimited tanojo...@googlemail.com wrote: Hello everyone, I encountered a few more problems while creating my system-wide makro program. 1) I can't load my dll with LoadLibraryW, only LoadLibraryA. Why? How are you passing the DLL filename to LoadLibraryA/W? Are you passing a string literal, i.e. LoadLibraryW(C:\\folder\dllname.dll); Have you tried the string literal suffix 'w', e.g. LoadLibraryW(C:\\folder\dllname.dllw); R