Void initialization
Using D1, I have a program that creates tons of float[] ; for performance reasons, I would like them to be uninitialized. I've tried replacing float[] f = new float[x]; by float[] f = cast(float[])std.gc.malloc(x*4); Unfortunately I keep running into Access violation and sometimes Array bounds error. I've tried adding setTypeInfo(typeid(float), f.ptr); and hasNoPointer(f.ptr); which didn't work. However f[] = float.nan; solved the problem, but kinda defeats the purpose of using malloc... What am I doing wrong?
Re: Void initialization
Am 19.12.2011, 13:04 Uhr, schrieb Bear joanylepri...@yahoo.fr: Using D1, I have a program that creates tons of float[] ; for performance reasons, I would like them to be uninitialized. std.array.uninitializedArray
Re: delegate, template and alias
== Quote from Philippe Sigaud (philippe.sig...@gmail.com)'s article On Sun, Dec 18, 2011 at 14:13, Heromyth bitwo...@qq.com wrote: I have a delegate as a parameter in a function which is a template function. And I want to use alias for the delegate parameter. Is there a better way for this? I suppose you do *not*want the commented line? You can extract a template parameter with an is() expression. But the extracted type is only accessible inside a static if. Solution: expose it through an alias: template AsynchronousActionParam(T) { static if (is(T t == void delegate(U), U)) alias U AsynchronousActionParam ; else static assert(false, Bad AsynchronousActionParam call: ~ T.stringof); } class TestC { int b = 3; void test(F)(F func ) if (is(AsynchronousActionParam!F)) { static if (is(AsynchronousActionParam!F == string)) func(It's me); else writeln(test called with void delegate( ~ AsynchronousActionParam!F ~ ).); } this(int x) { b = x; } } void main() { auto c = new TestC(3); void foo(string s) { writeln(foo: , s);} c.test(foo); } Thanks greatly. Your code makes me understanding D's template much more. The template in D is so amazing. writeln(test called with void delegate( ~ AsynchronousActionParam!F ~ ).); writeln(test called with void delegate( ~ AsynchronousActionParam!F.stringof ~ ).); I suppose you do *not*want the commented line? I want to convert a delegate type define in C# to D's, as such: public delegate void AsynchronousActionT(T argument, AsyncContinuation asyncContinuation); public static void ForEachItemSequentiallyT(IEnumerableT items, AsyncContinuation asyncContinuation, AsynchronousActionT action) { .. }
Re: delegate, template and alias
== Quote from Heromyth (bitwo...@qq.com)'s article == Quote from Philippe Sigaud (philippe.sig...@gmail.com)'s article I suppose you do *not*want the commented line? I want to convert a delegate type define in C# to D's, as such: public delegate void AsynchronousActionT(T argument, AsyncContinuation asyncContinuation); public static void ForEachItemSequentiallyT(IEnumerableT items, AsyncContinuation asyncContinuation, AsynchronousActionT action) { .. } Woo, I got it. template AsynchronousAction(T) { alias void delegate(T argument) AsynchronousAction; } public class TestC { int b = 3; //void test(T)(void delegate(T argument) func ) void test(T)(AsynchronousAction!(T) func ) { static if(is(T == string)) func(It's me); } this(int x) { b = x; } }
Re: Array expanding
On Sun, 18 Dec 2011 18:42:31 -0500, Jonathan M Davis jmdavisp...@gmx.com wrote: On Sunday, December 18, 2011 22:12:07 RenatoL wrote: Reading the book from Alexandrescu we can find this (page 103-104, at least in my edition): Expanding arrays has a couple of subtleties that concern possible reallocation of the array. Consider: auto a = [87, 40, 10, 2]; auto b = a; // Now a and b refer to the same chunk a ~= [5, 17]; // Append to a a[0] = 15; // Modify a[0] assert(b[0] == 15); // Pass or fail? it seems natural that the test is ok but it is not... if we read more we find: D leaves~= the freedom of either expanding by reallocation or opportunistically expanding in place if there is enough unused memory at the end of the current array. At a first glance this seems to be a serious issue... it seems hard to accept that b can lost its connection to a in a silent mode due to a reallocation Is there a safe mode to do this for large arrays? Read this: http://www.dsource.org/projects/dcollections/wiki/ArrayArticle In particular, this section covers the issue: http://www.dsource.org/projects/dcollections/wiki/ArrayArticle#Determinism And this section covers the additional functions that give you more info about the underlying array type: http://www.dsource.org/projects/dcollections/wiki/ArrayArticle#SliceMembersandtheAppender -Steve
Re: Void initialization
On Mon, 19 Dec 2011 07:04:20 -0500, Bear joanylepri...@yahoo.fr wrote: Using D1, I have a program that creates tons of float[] ; for performance reasons, I would like them to be uninitialized. I've tried replacing float[] f = new float[x]; by float[] f = cast(float[])std.gc.malloc(x*4); this is wrong. a float[] slice is actually a struct, whereas gc.malloc returns a pointer. What you have done is cast a pointer into a pointer+length struct, leaving anyones guess as to what the length is set to. I don't even know why this compiles... A slice is a pointer + length, and you can slice a pointer to add a length to it. Follow bearophile's suggestion. However f[] = float.nan; solved the problem, but kinda defeats the purpose of using malloc... What am I doing wrong? If this works, it's not doing what you think :) -Steve
Re: Void initialization
gc.malloc actually returns void[] Bearophile's suggestion seems to work though, but it doesn't seem to improve performance for some reason... I guess I'll have to find some other way to make my prog quicker.
Re: delegate, template and alias
On Mon, Dec 19, 2011 at 15:35, Heromyth bitwo...@qq.com wrote: Woo, I got it. What's the difference with your first post?
Re: delegate, template and alias
On 12/19/2011 06:46 PM, Philippe Sigaud wrote: On Mon, Dec 19, 2011 at 15:35, Heromythbitwo...@qq.com wrote: Woo, I got it. What's the difference with your first post? He uses an eponymous template now.
Allocating memory in D shared library when accessed from C++
Hello everyone, I would like to ask you about linking D shared objects (.dll and .so) from a C++ program. Say I have this C++ loader: typedef int (*MagicFunction) (); HMODULE handle = LoadLibraryA(DLibrary.dll); if (handle) { MagicFunction fn = (MagicFunction) GetProcAddress(handle, _magicFunction); std::coutfn()std::endl; } and this D library: class Something {} export extern (C) int magicNumber() { Something desc = new Something(); return 9; } extern (Windows) BOOL DllMain(HINSTANCE hInstance, ULONG ulReason, LPVOID pvReserved) { final switch (ulReason) { case DLL_PROCESS_ATTACH: g_hInst = hInstance; dll_process_attach( hInstance, true ); break; case DLL_PROCESS_DETACH: dll_process_detach( hInstance, true ); break; case DLL_THREAD_ATTACH: dll_thread_attach( true, true ); break; case DLL_THREAD_DETACH: dll_thread_detach( true, true ); break; } return true; } then whenever the code reaches the call: Something desc = new Something(); I get 'Access violation reading location 0x...' I thought that the GC is angry with me, so I have tried to use malloc, but to no avail. Error is the same... Can you please give me a hint what I am doing wrong? Also I am curious why is the first name of exported function underscored and all the others are not. Thanks for your time. Martin
Re: Void initialization
On 2011-12-19 18:24, Bear wrote: gc.malloc actually returns void[] Bearophile's suggestion seems to work though, but it doesn't seem to improve performance for some reason... I guess I'll have to find some other way to make my prog quicker. You can always make the variable uninitialized using void, don't know if that what is what you're looking for. float[] f = void; -- /Jacob Carlborg
Re: Allocating memory in D shared library when accessed from C++
Check if GetProcAddress returns null? It seems to me you're looking for _magicFunction but defining magicNumber, two different names.
Re: Void initialization
On Mon, 19 Dec 2011 12:24:18 -0500, Bear joanylepri...@yahoo.fr wrote: gc.malloc actually returns void[] http://www.d-programming-language.org/phobos/core_memory.html#malloc Looks like void* to me... Or is there another function I'm not aware of? I think it should be GC.malloc, not gc.malloc, so maybe I'm missing something... Bearophile's suggestion seems to work though, but it doesn't seem to improve performance for some reason... I guess I'll have to find some other way to make my prog quicker. Actually, an issue with bearophile's suggestion is that it allocates a block marked as containing pointers. Such a block is bulk-initialized to 0. Try this: float[] f = (cast(float*)GC.malloc(x * TF.sizeof, GC.BlkAttr.NO_SCAN))[0 .. x]; This will leave the memory uninitialized. And depending on the usage, this optimization may or may not make a huge difference. -Steve
Re: newbie question: Can D do this?
On 19.12.2011 17:17, clk wrote: 1) Does D support something like the javascript 1.8 destructuring assigment (multiple assigment in python): [a, b] = [b, a]; I don't think so, but you can do something like this with templates: void swap(alias a, alias b)() { auto t = a; a = b; b = t; } int a = 1, b = 2; swap!(a, b); assert(a == 2); assert(b == 1); 2) D doesn't seem to support the list comprehension syntax available in python and javascript. Is this correct? [f(x) for x in list if condition] Don't think so. You can use std.algorithm, but it's a bit harder to read: auto arr = [1,2,3,4,5,6]; auto res = array(pipe!(filter!a3, map!a*2)(arr)); assert(res == [8,10,12]); // or auto res2 = array(map!a*2(filter!a3(arr))); assert(res2 == [8,10,12]); But I'm a newbie myself.
Re: Allocating memory in D shared library when accessed from C++
On 19/12/2011 18:01, Andrej Mitrovic wrote: Check if GetProcAddress returns null? It seems to me you're looking for _magicFunction but defining magicNumber, two different names. that's be it. can't remember the rules for whether it will have a leading underscore, but you can always use dependency walker to find out: http://dependencywalker.com/ -- My enormous talent is exceeded only by my outrageous laziness. http://www.ssTk.co.uk
Re: newbie question: Can D do this?
On Monday, December 19, 2011 11:17:43 clk wrote: Hello, I'm new to this mailing list. I'm trying to learn D to eventually use it in production code. I'm a little bit intimidated by the fact that the topics in the d-learn list look rather advanced to a newbie like me. I have 3 fairly simple questions: 1) Does D support something like the javascript 1.8 destructuring assigment (multiple assigment in python): [a, b] = [b, a]; No. You'd have to use std.algorithm.swap. 2) D doesn't seem to support the list comprehension syntax available in python and javascript. Is this correct? [f(x) for x in list if condition] No, but you can do similar stuff with std.algorithm. auto transformed = map!func(filter!cond(list)); 3) D's slice operator apparently doesn't allow the use of a stride other than unity as is allowed with fortran and matlab. Is there a way to implement this feature so that [1, 2, 3, 4, 5][0..$:2] would refer to [1, 3, 5], etc..., where 2 is the non unit stride. Or is the find function from std.algorithm the only option to achieve the same behavior. Use std.range.stride. If you want a new array from it, then use std.array.array on the result. Otherwise, it's a range (see http://www.informit.com/articles/printerfriendly.aspx?p=1407357 for a general explanation of the concept of ranges) but not an array. e.g. auto arr = array(stride([1, 2, 3, 4, 5], 2)); - Jonathan M Davis
Re: newbie question: Can D do this?
On 12/19/2011 08:17 AM, clk wrote: I'm a little bit intimidated by the fact that the topics in the d-learn list look rather advanced to a newbie like me. We need more newbie topics here! :) 1) Does D support something like the javascript 1.8 destructuring assigment (multiple assigment in python): [a, b] = [b, a]; No multiple assignment like that. But useful approarches exist for most needs, like the swap that simendsjo has shown. 2) D doesn't seem to support the list comprehension syntax available in python and javascript. Is this correct? [f(x) for x in list if condition] List comprehension is not part of the language. import std.algorithm; void f(int x) {} bool condition(int x) { return true; } void main() { auto list = [ 0, 1, 2 ]; map!f(filter!condition(list)); } You can define f and condition within the body of main(). It is possible to use function literals as well: import std.algorithm; void main() { auto list = [ 0, 1, 2 ]; map!((x){ /* ... this is f(x) ...*/ })(filter!((x) { return true; /* ... condition ... */ })(list)); } 3) D's slice operator apparently doesn't allow the use of a stride other than unity as is allowed with fortran and matlab. Is there a way to implement this feature so that [1, 2, 3, 4, 5][0..$:2] would refer to [1, 3, 5], etc..., where 2 is the non unit stride. Or is the find function from std.algorithm the only option to achieve the same behavior. std.range.stride does that: import std.range; // ... stride([1, 2, 3, 4, 5], 2) I find the 3 features above extremely convenient in every day coding. Thanks, -clk Ali
Re: newbie question: Can D do this?
On 12/19/2011 09:17 AM, clk wrote: Hello, I'm new to this mailing list. I'm trying to learn D to eventually use it in production code. I'm a little bit intimidated by the fact that the topics in the d-learn list look rather advanced to a newbie like me. I have 3 fairly simple questions: 1) Does D support something like the javascript 1.8 destructuring assigment (multiple assigment in python): [a, b] = [b, a]; I would love multiple assignment like this, but it's tricky. But your usage isn't really multiple assignment as much as it is a swap. What I'd love is something like this: [a, b, c] = [get_a(), get_b(), get_c()]; Or [a, b, c] = [to!(int)(argv[1]), some_other_value, argv[4]); 2) D doesn't seem to support the list comprehension syntax available in python and javascript. Is this correct? [f(x) for x in list if condition] No, D's syntax is very C-ish. I don't expect syntax like this to ever show up (though what you are doing is possible with things like std.algorithm) 3) D's slice operator apparently doesn't allow the use of a stride other than unity as is allowed with fortran and matlab. Is there a way to implement this feature so that [1, 2, 3, 4, 5][0..$:2] would refer to [1, 3, 5], etc..., where 2 is the non unit stride. Or is the find function from std.algorithm the only option to achieve the same behavior. Ya, std.range, like Ali said. I find the 3 features above extremely convenient in every day coding. Thanks, -clk
Re: newbie question: Can D do this?
On Mon, 19 Dec 2011 17:17:43 +0100, clk c...@clksoft.com wrote: Hello, I'm new to this mailing list. I'm trying to learn D to eventually use it in production code. I'm a little bit intimidated by the fact that the topics in the d-learn list look rather advanced to a newbie like me. I have 3 fairly simple questions: 1) Does D support something like the javascript 1.8 destructuring assigment (multiple assigment in python): [a, b] = [b, a]; This, or something quite like it, was covered on Saturday in the thread Alias/Ref Tuples ?. This works (but is hardly as elegant as Python's syntax: import std.typetuple : TypeTuple; import std.typecons : tuple; TypeTuple!(a, b) = tuple(b,a);
Re: newbie question: Can D do this?
On 12/19/2011 10:39 AM, Jonathan M Davis wrote: it's a range (see http://www.informit.com/articles/printerfriendly.aspx?p=1407357 for a general explanation of the concept of ranges) That's a great article.[1] I hope that this chapter is more beginner-friendly: http://ddili.org/ders/d.en/ranges.html Ali [1] Andrei's article has a Turkish translation as well: http://ddili.org/makale/eleman_erisimi_uzerine.html
Re: delegate, template and alias
On Mon, Dec 19, 2011 at 18:49, Timon Gehr timon.g...@gmx.ch wrote: On 12/19/2011 06:46 PM, Philippe Sigaud wrote: On Mon, Dec 19, 2011 at 15:35, Heromythbitwo...@qq.com wrote: Woo, I got it. What's the difference with your first post? He uses an eponymous template now. Ah yes, thanks. Strange, I'm pretty sure I used the eponymous trick and it didn't work, for some reason. Anyway, Heromyth, I'm slowly working on a D template tutorial. The current pdf is at: https://github.com/PhilippeSigaud/D-templates-tutorial/blob/master/dtemplates.pdf (click on View Raw to download). It's still incomplete. I'll work on it during the holidays and post on D.announce to get some feedback on it, but you're welcome if you want to give it a try. Philippe
Re: Allocating memory in D shared library when accessed from C++
Dne 19.12.2011 19:39, Simon napsal(a): On 19/12/2011 18:01, Andrej Mitrovic wrote: Check if GetProcAddress returns null? It seems to me you're looking for _magicFunction but defining magicNumber, two different names. that's be it. can't remember the rules for whether it will have a leading underscore, but you can always use dependency walker to find out: http://dependencywalker.com/ Hi guys, thanks for your response... but it is not the problem. I must have made a mistake writing this down. It actualy returns a procedure address and the procedure is called. It lands inside export extern (C) int magicNumber() and crashes when attempting to allocate memory for Something. I have used dependency walker, that is why I asked why only the first function is exported with underscore and the others are not. Martin
Re: Allocating memory in D shared library when accessed from C++
It actualy returns a procedure address and the procedure is called. It lands inside export extern (C) int magicNumber() and crashes when attempting to allocate memory for Something. Did you properly initialize druntime?
Re: Allocating memory in D shared library when accessed from C++
Dne 19.12.2011 23:09, Trass3r napsal(a): It actualy returns a procedure address and the procedure is called. It lands inside export extern (C) int magicNumber() and crashes when attempting to allocate memory for Something. Did you properly initialize druntime? As I am just starting with D, the most precise answer I can give you is: I don't know... how do I tell? Or in another way - the code for D library is almost complete except for imports. The rest was done for me by Visual D. Martin
Re: Allocating memory in D shared library when accessed from C++
Am 19.12.2011, 23:13 Uhr, schrieb Martin Drašar dra...@ics.muni.cz: Dne 19.12.2011 23:09, Trass3r napsal(a): It actualy returns a procedure address and the procedure is called. It lands inside export extern (C) int magicNumber() and crashes when attempting to allocate memory for Something. Did you properly initialize druntime? As I am just starting with D, the most precise answer I can give you is: I don't know... how do I tell? Or in another way - the code for D library is almost complete except for imports. The rest was done for me by Visual D. It's explained there: http://www.dlang.org/dll.html
Re: delegate, template and alias
On 12/19/2011 09:30 PM, Philippe Sigaud wrote: On Mon, Dec 19, 2011 at 18:49, Timon Gehrtimon.g...@gmx.ch wrote: On 12/19/2011 06:46 PM, Philippe Sigaud wrote: On Mon, Dec 19, 2011 at 15:35, Heromythbitwo...@qq.comwrote: Woo, I got it. What's the difference with your first post? He uses an eponymous template now. Ah yes, thanks. Strange, I'm pretty sure I used the eponymous trick and it didn't work, for some reason. Anyway, Heromyth, I'm slowly working on a D template tutorial. The current pdf is at: https://github.com/PhilippeSigaud/D-templates-tutorial/blob/master/dtemplates.pdf (click on View Raw to download). It's still incomplete. I'll work on it during the holidays and post on D.announce to get some feedback on it, but you're welcome if you want to give it a try. Philippe Looks very good. Knowing it is a work in progress, I will already give some feedback: You have a typo on page 15: static if (is(T t = U[], U)) // is T an array of U, for some type U? You probably meant to write static if (is(T t == U[], U)) // is T an array of U, for some type U? On page 18, I think your explanation why you used .power instead of power is not yet entirely accurate. The only reason why it is needed is because you are defining an eponymous template that hides the global template. Also on page 18: 'Note that this template will work not only for unary (one argument) functions but also for n-args functions,' The implementation given does not work for n-args functions because functions cannot return a tuple. Page 23: 'Note that flatten works perfectly on ranges too, but is not lazy' Ranges don't have the concatenation operator, so it will not work. Page 25: 'And due to (to my eyes) a bug in alias, you cannot alias them to a symbol: alias (a){ return a;} Id; // Error' It is a restriction that the current D grammar has. You can do this: alias ID!((a){ return a;}) Id; where ID is template ID(alias X){alias X ID;} Page 25: 'Since they are delegates, they can capture local symbols, as long as these are defined at compile-time:' They can even capture local symbols that don't have a compile-time value. For example: auto foo(alias s)(){return s();} void main() { int x = 2; writeln(foo!({return x;})()); // prints '2' } And the link is purely symbolic, no closures or the like are allocated. What the compiler effectively does is in the lines of this: void main() { int x = 2; auto dgliteral() { return x; } // {return x;} auto foo(){ return dgliteral(); } // foo!({return x}) writeln(foo()); // call template instance } This is one of the most powerful features of D templates: They are instantiated in the most local scope that is required for them to work. Page 38: 'By the way, strangely enough, though you cannot declare ‘pure’ templates inside functions, you can declare struct templates.' Do you want to file a bug report against this? This has bothered me a few times too. Page 39: Template this parameters are also useful to determine how the type of the this reference is qualified, (const/immutable/shared/inout) Page 67: 'mixin template Concatenate() { Tuple!(This, U) opBinary(string op, this This)(This u) if (op == ~) { return tuple(this, u); } Tuple!(U, This) opBinaryRight(string op, this This)(This u) if (op == ~) { return tuple(u, this); } }' I think what you meant was this: mixin template Concatenate() { Tuple!(This, U) opBinary(string op, this This)(U u) if (op == ~) { return tuple(this, u); } Tuple!(U, This) opBinaryRight(string op, this This)(U u) if (op == ~) { return tuple(u, this); } } Page 76: 'At the time of this writing, the limitations are mostly: no classes and no exceptions (and so, no enforce).' DMD 2.057 supports classes and exceptions in CTFE =) Page 82: I'd be careful with that table. Probably most of the ones you marked as 'No' are actually 'Yes' when doing some clever things with is(typeof())? Page 90: '34 Extending a Class' Maybe add a note that this does not work across module boundaries and therefore has not much practical use. Page 90: 'return; // or return void;' That looks like it was actual syntax. Page 94/95: 'Strangely, you can only use it with the is(Type identifier, ...) syntax: you must have identifier.' 'For me, the main limitation is that template tuple parameters are not accepted. Too bad.' Do you want to file the enhancement requests, or should I file them? Having those would increase the consistency of the language. Keep up the good work!
Re: Allocating memory in D shared library when accessed from C++
Dne 20.12.2011 0:02, Trass3r napsal(a): Am 19.12.2011, 23:13 Uhr, schrieb Martin Drašar dra...@ics.muni.cz: Dne 19.12.2011 23:09, Trass3r napsal(a): It actualy returns a procedure address and the procedure is called. It lands inside export extern (C) int magicNumber() and crashes when attempting to allocate memory for Something. Did you properly initialize druntime? As I am just starting with D, the most precise answer I can give you is: I don't know... how do I tell? Or in another way - the code for D library is almost complete except for imports. The rest was done for me by Visual D. It's explained there: http://www.dlang.org/dll.html Well as far as I can tell, the runtime is initialized with call to Runtime.initialize(). This call is executed inside dll_process_attach here: extern (Windows) BOOL DllMain(HINSTANCE hInstance, ULONG ulReason, LPVOID pvReserved) { final switch (ulReason) { case DLL_PROCESS_ATTACH: g_hInst = hInstance; dll_process_attach( hInstance, true ); break; so I would say that the runtime is properly initialized. Martin
Re: Void initialization
On Mon, 19 Dec 2011 18:52:44 +0100 Jacob Carlborg d...@me.com wrote: You can always make the variable uninitialized using void, don't know if that what is what you're looking for. float[] f = void; He is trying to create an array where the elements are not initialized.
Re: Allocating memory in D shared library when accessed from C++
test.cpp: http://www.ideone.com/uh7vN DLibrary.d: http://www.ideone.com/fOLN8 $ g++ test.cpp $ dmd -ofDLibrary.dll DLibrary.d $ a.exe $ 9
Re: newbie question: Can D do this?
On Monday, 19 December 2011 at 19:01:10 UTC, Simen Kjærås wrote: import std.typetuple : TypeTuple; import std.typecons : tuple; TypeTuple!(a, b) = tuple(b,a); There is a pull request implementing multiple variable declarations: https://github.com/D-Programming-Language/dmd/pull/341 However, the right hand side must still be a tuple.
Re: Void initialization
On 2011-12-20 01:34, Jesse Phillips wrote: On Mon, 19 Dec 2011 18:52:44 +0100 Jacob Carlborgd...@me.com wrote: You can always make the variable uninitialized using void, don't know if that what is what you're looking for. float[] f = void; He is trying to create an array where the elements are not initialized. Ah, I see. -- /Jacob Carlborg