Re: Static array with parameter based size?

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

On Wednesday, 12 July 2017 at 05:45:13 UTC, Miguel L wrote:

Hi

I need to create a non-dynamic array like this

void f(int x)
{
int[x] my_array;
...

this does not compile as x value needs to be known at compile 
time. The closest to this I can get is:


void f(int x)
{
int[] my_array;
my_array.length=x;

but I don't really need a dynamic array as length is not going 
to change inside f.


What is the best way to do this?

Also what is it possible in D to write a function that accepts 
an static array of any size?


Thanks in advance


Sorry, this post is duplicated. Yesterday forum was not working 
and i received an error when i was trying to post it. Please 
ignore it.


Static array with parameter based size?

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

Hi

I need to create a non-dynamic array like this

void f(int x)
{
int[x] my_array;
...

this does not compile as x value needs to be known at compile 
time. The closest to this I can get is:


void f(int x)
{
int[] my_array;
my_array.length=x;

but I don't really need a dynamic array as length is not going to 
change inside f.


What is the best way to do this?

Also what is it possible in D to write a function that accepts an 
static array of any size?


Thanks in advance


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

2017-07-11 Thread Brandon Buck via Digitalmars-d-learn
On Wednesday, 12 July 2017 at 02:06:41 UTC, Steven Schveighoffer 
wrote:
I do agree it's not intuitive for an initializer, especially 
when:


auto a = [1, 2, 3]; // typeof(a) == int[]
short[] b = [1, 2, 3]; // works


Thank you for getting back to me, that's where my train of 
thought was going. While I know it's not _really_ valid to say 
"this other language does it," my experience does hail from 
elsewhere where this would be perfectly legal.



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


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



auto d = new Dog;
Animal a = d;
writefln("%x, %x", cast(void*)d, cast(void*)a); // prints 2 
different addresses


That's also an interesting observation.



Re: mysql-native ResultRange + map

2017-07-11 Thread crimaniak via Digitalmars-d-learn
On Tuesday, 11 July 2017 at 22:46:00 UTC, Steven Schveighoffer 
wrote:

On 7/5/17 12:04 PM, crimaniak wrote:

...
Because of the temporary copy likely inside map closes the 
connection.


See the bug I reported: 
https://github.com/mysql-d/mysql-native/issues/117
 Yes, it seems to be the same issue. (BTW, then I tried filter() 
just for curiosity and have the same problem).


I work around this in my code by moving the temporary copy. But 
I'm sorry to say you likely will not be able to fix map.
 I have WEB application (no big recordsets to transfer), so, for 
now, I "fix" it inside of my sql wrapper: just load recordset to 
an array and give it instead of ResultRange. I don't like it, but 
it works and all shit is localized in one place.


I think Nick's comment is interesting, "Seems that using struct 
dtors without refcounting should in general be regarded as a 
code smell?"


It's a good question. I've also always added ref counting when 
wanting to "auto close" a struct's resources. In fact, I can't 
really think of a good use of destructors for structs that 
isn't for reference counting itself.


I don't think so. There is architecture problem: non-copyable by 
nature resource represented by copyable struct. We need 
non-copyable class/object semantics here or have to emulate it if 
using the struct to have the correct behavior. It's fully o.k. to 
get some resources required by _this exact copy_ of struct in the 
constructor and then release it in the destructor. For example of 
good use of destructors: position in some game, requires 
non-fixed space to store itself. We want to make copies of 
positions, apply some movies to them and then make copies again 
to search in positions tree. Copy constructor will malloc some 
space and copy source position data, the destructor will free 
this space, and we don't need reference counting here.






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

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

On 7/11/17 9:27 PM, Brandon Buck wrote:
I apologize if this has been touched on before, I'm not quite sure what 
to search for and what I did try didn't bring anything up.


Okay, so I'm learning D, using the D Tour flow and I went over 
interfaces. Everything is making sense. I key in the example (as I like 
to copy it by hand and then run it locally instead of online) and I 
attempt to make a slight alteration. In the previous example, with base 
classes, the main method begins with:



Any[] anys = [
 new Integer(10),
 new Float(3.1415f)
];

Which makes sense. Integer and Float in that example are both inheriting 
from Any. So when doing the example with interfaces where Dog and Cat 
both inherit from the interface Animal, I first tried:


auto animals = [
 new Dog,
 new Cat
];

But got this error:

interfaces.d(51): Error: no property 'multipleNoise' for type 
'object.Object'


Which implies (to me) the auto inferred object.Object, this makes sense 
though. Without basic type inspection they're both classes and 
object.Object is the most reasonable parent of them both. Fine. I 
adjusted my code to better match the class example:


Animal[] animals = [
 new Dog,
 new Cat
];

Surely this works:

interfaces.d(47): Error: cannot implicitly convert expression ([new Dog, 
new Cat]) of type Object[] to Animal[]


Different _message_ but same issue. It's inferring Object[]. I've told 
it explicitly that it's an Animal[], and both classes inherit from 
Animal (as the solution and the example on the tour page) demonstrate:


In some cases, the declaration does not participate in the type 
inference. It's still looking at the expression [new Dog, new Cat] 
separately from the declaration of the array.


The problem is that it has multiple "trees" to go down. Both can be 
Objects, both can be Animals, which one did you really mean?


You can override this with a cast:

auto animals = cast(Animal[])[new Dog, new Cat];

Or you can cast the first item to tell the inference which tree to go down.

auto animals = [cast(Animal)new Dog, new Cat];

I do agree it's not intuitive for an initializer, especially when:

auto a = [1, 2, 3]; // typeof(a) == int[]
short[] b = [1, 2, 3]; // works

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

So they can be assigned to Animal fine, but even using them in an 
expression tagged with Animal[] still produces an Object[] value. Is 
this intentional? It feels unintuitive. I understand why auto infers 
Object[] and that make sense, but if I'm using the actual type 
(Animal[]) and can work the long way around to the same type (the last 
example), why can't I do it via direct assignment to Animal[]?


Note that an interface reference is not the same as a class reference.

You can see the difference here:

auto d = new Dog;
Animal a = d;
writefln("%x, %x", cast(void*)d, cast(void*)a); // prints 2 different 
addresses


An interface reference can't be "reinterpret cast" to an Object, or even 
another interface, it just will result in crashes. So you can't cast an 
array like that either, you'd have to copy the array, or modify it.


-Steve


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

2017-07-11 Thread Brandon Buck via Digitalmars-d-learn
I apologize if this has been touched on before, I'm not quite 
sure what to search for and what I did try didn't bring anything 
up.


Okay, so I'm learning D, using the D Tour flow and I went over 
interfaces. Everything is making sense. I key in the example (as 
I like to copy it by hand and then run it locally instead of 
online) and I attempt to make a slight alteration. In the 
previous example, with base classes, the main method begins with:



Any[] anys = [
new Integer(10),
new Float(3.1415f)
];

Which makes sense. Integer and Float in that example are both 
inheriting from Any. So when doing the example with interfaces 
where Dog and Cat both inherit from the interface Animal, I first 
tried:


auto animals = [
new Dog,
new Cat
];

But got this error:

interfaces.d(51): Error: no property 'multipleNoise' for type 
'object.Object'


Which implies (to me) the auto inferred object.Object, this makes 
sense though. Without basic type inspection they're both classes 
and object.Object is the most reasonable parent of them both. 
Fine. I adjusted my code to better match the class example:


Animal[] animals = [
new Dog,
new Cat
];

Surely this works:

interfaces.d(47): Error: cannot implicitly convert expression 
([new Dog, new Cat]) of type Object[] to Animal[]


Different _message_ but same issue. It's inferring Object[]. I've 
told it explicitly that it's an Animal[], and both classes 
inherit from Animal (as the solution and the example on the tour 
page) demonstrate:


Animal dog = new Dog;
Animal cat = new Cat;
Animal[] animals = [dog, cat];

So they can be assigned to Animal fine, but even using them in an 
expression tagged with Animal[] still produces an Object[] value. 
Is this intentional? It feels unintuitive. I understand why auto 
infers Object[] and that make sense, but if I'm using the actual 
type (Animal[]) and can work the long way around to the same type 
(the last example), why can't I do it via direct assignment to 
Animal[]?


Re: 'typeof' not printing template arguments.

2017-07-11 Thread Deech via Digitalmars-d-learn

On Wednesday, 12 July 2017 at 00:44:38 UTC, Deech wrote:

Hi all,
I've been learning D for a few weeks by reading through 
Programming In D [1] and had a question about Eponymous 
Template section [2]. Here's the example:


```
template LargerOf(A, B) {
  static if (A.sizeof < B.sizeof) {
alias LargerOf = B;

  } else {
alias LargerOf = A;
  }
}

LargerOf!(A, B) calculate(A, B)(A a, B b) {
  LargerOf!(A, B) result;
  return result;
}

pragma(msg, typeof(calculate));
```

At build time instead of printing:
```
LargerOf!(A, B)(A, B)(A a, B b)
```

it prints:
```
double(double lhs, double rhs)
```

Is there some reason it specializes to `double`?

-deech
[1] http://ddili.org/ders/d.en/index.html
[2] http://ddili.org/ders/d.en/templates_more.html


nm, dumb mistake on my part. I had a `calculate` at the top of 
the file and missed it. Sorry.


'typeof' not printing template arguments.

2017-07-11 Thread Deech via Digitalmars-d-learn

Hi all,
I've been learning D for a few weeks by reading through 
Programming In D [1] and had a question about Eponymous Template 
section [2]. Here's the example:


```
template LargerOf(A, B) {
  static if (A.sizeof < B.sizeof) {
alias LargerOf = B;

  } else {
alias LargerOf = A;
  }
}

LargerOf!(A, B) calculate(A, B)(A a, B b) {
  LargerOf!(A, B) result;
  return result;
}

pragma(msg, typeof(calculate));
```

At build time instead of printing:
```
LargerOf!(A, B)(A, B)(A a, B b)
```

it prints:
```
double(double lhs, double rhs)
```

Is there some reason it specializes to `double`?

-deech
[1] http://ddili.org/ders/d.en/index.html
[2] http://ddili.org/ders/d.en/templates_more.html


Re: Foreign threads in D code.

2017-07-11 Thread Igor Shirkalin via Digitalmars-d-learn

On Tuesday, 11 July 2017 at 06:18:44 UTC, Biotronic wrote:

On Monday, 10 July 2017 at 20:03:32 UTC, Igor Shirkalin wrote:

[...]


If DRuntime is not made aware of the thread's existence, the 
thread will not be stopped by the GC, and the GC might collect 
memory that the thread is referencing on the stack or in non-GC 
memory. Anything allocated by the GC would still be scanned.


To inform DRuntime about your thread, you should call 
thread_attachThis:


https://dlang.org/phobos/core_thread.html#.thread_attachThis

As pointed out in the documentation of thread_attachThis, you 
might also want to call rt_moduleTlsCtor, to run thread local 
static constructors. Depending on your usage, this might not be 
necessary.


--
  Biotronic


Thanks for very useful information!


Re: mysql-native ResultRange + map

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

On 7/5/17 12:04 PM, crimaniak wrote:

Hi all!

After some hard time with debugging, I found ResultRange returned by 
query() and Prepared::query() of mysql-native package can't be combined 
with map() because after map() it becomes empty resultset.



[snip]
As you see simple each() and foreach() works, but all examples with 
map() involved always empty. Can anybody explain such strange behavior?




Because of the temporary copy likely inside map closes the connection.

See the bug I reported: https://github.com/mysql-d/mysql-native/issues/117

I work around this in my code by moving the temporary copy. But I'm 
sorry to say you likely will not be able to fix map.


I think Nick's comment is interesting, "Seems that using struct dtors 
without refcounting should in general be regarded as a code smell?"


It's a good question. I've also always added ref counting when wanting 
to "auto close" a struct's resources. In fact, I can't really think of a 
good use of destructors for structs that isn't for reference counting 
itself.


-Steve


Re: Cannot dup an associative array but why?

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

On 07/11/2017 01:25 PM, Jean-Louis Leroy wrote:
> On Tuesday, 11 July 2017 at 17:20:33 UTC, Ali Çehreli wrote:
>
>> @Virtual("t", "d", "w")
>> string fight(Character t, Dragon d, Hands w) {
>> return "you just killed a dragon with your bare hands. Incredible
>> isn't it?";
>> [...]
>> mixin ProcessMethods();
>
> Great suggestion! I think this could work:
>
>   string fight(virtual!Character, virtual!Creature, virtual!Device); //
> declares method
>
>   // define implemention:
>   string fight(Character t, Dragon d, Hands w);
>
>   mixin ProcessMethods();
>
> How do you find the current module inside ProcessMethods?

Default template and function arguments are resolved at instantiation 
site, which means __MODULE__ would resolve automatically to the caller's 
module. For example, if you have this module:


--
module a;

mixin template ProcessMethods(string mod = __MODULE__) {
enum s = "Working with " ~ mod;
}
--

The user can simply mix it in:

--
module deneme;

import a;

mixin ProcessMethods;

void main() {
pragma(msg, s);
}
--

And the string has the user's module 'deneme':

Working with deneme

Ali



Re: Cannot dup an associative array but why?

2017-07-11 Thread Jean-Louis Leroy via Digitalmars-d-learn

On Tuesday, 11 July 2017 at 17:20:33 UTC, Ali Çehreli wrote:


@Virtual("t", "d", "w")
string fight(Character t, Dragon d, Hands w) {
return "you just killed a dragon with your bare hands. 
Incredible isn't it?";

[...]
mixin ProcessMethods();


Great suggestion! I think this could work:

  string fight(virtual!Character, virtual!Creature, 
virtual!Device); // declares method


  // define implemention:
  string fight(Character t, Dragon d, Hands w);

  mixin ProcessMethods();

How do you find the current module inside ProcessMethods?

There's a problem with the catch-all method though:

  string fight(Character a, Creature b, Device c) { }

This won't work because string fight(Character a, Creature b, 
Device c) is the method itself - it's generated by the library. 
We'll have to come up with a special syntax for it.


J-L



Re: Cannot dup an associative array but why?

2017-07-11 Thread Jean-Louis Leroy via Digitalmars-d-learn

On Tuesday, 11 July 2017 at 17:20:33 UTC, Ali Çehreli wrote:

That's some serious code you've written there and you must be 
happy that 'virtual' is not a keyword in D. ;)


Thanks. Haha I would have used virtual_ like I did in C++ ;-)


Maybe others can come up with ideas on a better syntax.


When it is presentable (I'm almost there) I plan to ask a review. 
I would welcome suggestions about the syntax - which is not too 
bad as it is now, I have been happily surprised with what is 
feasible. It even supports overloading methods.


The thing that annoys me most is having to pass a string to 
'method'. And attributes are not allowed on arguments. I wish I 
would make something like this work:


mixin method!(fight, string, virtual!Character, 
virtual!Creature, virtual!Device);


// or:
mixin method!(fight, string, @virtual Character, @virtual 
Creature, @virtual Device);


// even better
mixin method!(fight, function string(@virtual Character, 
@virtual Creature, @virtual Device));


// and if there is a catch-all implementation:
mixin method!(fight, function string(@virtual Character, 
@virtual Creature, @virtual Device) {

// body
}

I tried to get inspiration from Yes and No, considered using 
opDispatch, but I haven't found a way yet.


Just to get the conversation going and without thinking it 
through, how about something like the following?


struct Virtual(Args...) {
// ...
}

@Virtual("t", "d", "w")
string fight(Character t, Dragon d, Hands w) {
return "you just killed a dragon with your bare hands. 
Incredible isn't it?";

}


The 'virtual' qualifier applies to the arguments in the method 
declaration, not the specializations. Also, I prefer to keep the 
qualifiers stuck to the argument. It's clearer. Interesting idea 
though.


Then, something like the following which would parse the module 
to do its magic:


mixin ProcessMethods();


Very interesting. I don't like the repetition of 'mixin' in front 
of each 'method' and 'implementation'.


Hmmm...if ProcessMethods() can find @Virtual(...) functions can't 
it find functions that have virtual! parameters?


Re: pure factory function vs immutable(Foo)**

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

On 7/11/17 2:12 PM, ag0aep6g wrote:

On 07/10/2017 04:57 PM, ag0aep6g wrote:


alias T = int;

T** f(const T** input) pure
{
 T** output;
 return output;
}

void main()
{
 T i;
 T* p = 
 immutable T** r = f();
}


[...]
Now change `T` to `alias T = immutable int;`. The program gets 
rejected. The error message is: "cannot implicitly convert expression 
(f(& p)) of type immutable(int)** to immutable(int**)".


Filed an issue:
https://issues.dlang.org/show_bug.cgi?id=17635


I think this is a legitimate bug.

to make sure this is correct, I added:

pragma(msg, typeof(input).stringof);

And it prints const(immutable(int)**) (as I would have expected, but 
wasn't 100% sure).


So there is no way the input can be returned, as immutable(int)** cannot 
be implicitly converted from const(immutable(int)**).


I think this is just a missed case in the compiler.

-Steve


Re: How to add authentificaion method to request?

2017-07-11 Thread ikod via Digitalmars-d-learn

On Tuesday, 11 July 2017 at 12:15:39 UTC, Suliman wrote:
I am using dlang-requests. I need authentificate on 
https://scihub.copernicus.eu/dhus/login and than do some 
data-parsing.


MultipartForm form;
form.add(formData("login_username", "Suliman"));
form.add(formData("login_password", "123")); // changed
auto content = 
postContent("https://scihub.copernicus.eu/dhus/login;, form);

writeln("Output:");
writeln(content);

Return error about login pass. So it's seems that I need to add 
BasicAuthentication method type. But how to add it?



Browser console show next: https://snag.gy/VXaq2R.jpg


Hello,
Yo have to use Request object if you need to configure basic 
authentication.


MultipartForm form;
Request request;
request.authenticator = new BasicAuthentication("user", 
"passwd");

form.add(formData("login_username", "Suliman"));
form.add(formData("login_password", "123")); // changed
auto response = 
request.post("https://scihub.copernicus.eu/dhus/login;, form);

auto content = response.responseBody;
writeln("Output:");
writeln(content);



Re: pure factory function vs immutable(Foo)**

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

On 07/10/2017 04:57 PM, ag0aep6g wrote:


alias T = int;

T** f(const T** input) pure
{
 T** output;
 return output;
}

void main()
{
 T i;
 T* p = 
 immutable T** r = f();
}


[...]
Now change `T` to `alias T = immutable int;`. The program gets rejected. 
The error message is: "cannot implicitly convert expression (f(& p)) of 
type immutable(int)** to immutable(int**)".


Filed an issue:
https://issues.dlang.org/show_bug.cgi?id=17635


Re: Cannot dup an associative array but why?

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

On 07/10/2017 04:24 PM, Jean-Louis Leroy wrote:

> FYI, having a lot of fun. See
> 
https://github.com/jll63/meth.d/blob/experiments/source/meth/examples/adventure.d


I'm glad you're trying out multi-methods with D:

  https://github.com/jll63/meth.d/tree/experiments

That's some serious code you've written there and you must be happy that 
'virtual' is not a keyword in D. ;)


Maybe others can come up with ideas on a better syntax. Just to get the 
conversation going and without thinking it through, how about something 
like the following?


struct Virtual(Args...) {
// ...
}

@Virtual("t", "d", "w")
string fight(Character t, Dragon d, Hands w) {
return "you just killed a dragon with your bare hands. Incredible 
isn't it?";

}

Then, something like the following which would parse the module to do 
its magic:


mixin ProcessMethods();
// Can include 'static this()' for runtime initialization if necessary

Again though, this is just a thought about making the syntax more 
fluent. More for the others to think about it for me. :)


Ali



Re: dmd, vibe.d RAM usage when compiling.

2017-07-11 Thread Andre Pany via Digitalmars-d-learn

On Tuesday, 11 July 2017 at 16:04:52 UTC, SrMordred wrote:
I never notice this before, but i tried to put a basic hello 
world from vibe.d (like the one that are in the dlang front 
page examples now), into the most basic instance on google 
cloud (with 600mb of RAM) and the compilation returned

"Killed
dmd failed with exit code 137."

So I look at the RAM usage and saw that when compiling (with 
dub) it uses 550mb+.


So i´m unable to put hello world to work.

Aren´t this number a bit too high for a basic example?


https://github.com/rejectedsoftware/vibe.d/issues/1787

Same issue on Cloud Foundry;)

Single file compilation is slow but a worksround.

Kind regards
André


Re: dmd, vibe.d RAM usage when compiling.

2017-07-11 Thread Cym13 via Digitalmars-d-learn

On Tuesday, 11 July 2017 at 16:04:52 UTC, SrMordred wrote:
I never notice this before, but i tried to put a basic hello 
world from vibe.d (like the one that are in the dlang front 
page examples now), into the most basic instance on google 
cloud (with 600mb of RAM) and the compilation returned

"Killed
dmd failed with exit code 137."

So I look at the RAM usage and saw that when compiling (with 
dub) it uses 550mb+.


So i´m unable to put hello world to work.

Aren´t this number a bit too high for a basic example?


They're expected sadly. It's known that D's common style and 
especially templates quickly leads to huge memory usage. There is 
work in progress to mitigate the issue such as reducing the size 
of symbols within the binary but it's not available for the 
moment.


dmd, vibe.d RAM usage when compiling.

2017-07-11 Thread SrMordred via Digitalmars-d-learn
I never notice this before, but i tried to put a basic hello 
world from vibe.d (like the one that are in the dlang front page 
examples now), into the most basic instance on google cloud (with 
600mb of RAM) and the compilation returned

"Killed
dmd failed with exit code 137."

So I look at the RAM usage and saw that when compiling (with dub) 
it uses 550mb+.


So i´m unable to put hello world to work.

Aren´t this number a bit too high for a basic example?




Re: How to add authentificaion method to request?

2017-07-11 Thread Cym13 via Digitalmars-d-learn

On Tuesday, 11 July 2017 at 12:15:39 UTC, Suliman wrote:
I am using dlang-requests. I need authentificate on 
https://scihub.copernicus.eu/dhus/login and than do some 
data-parsing.


MultipartForm form;
form.add(formData("login_username", "Suliman"));
form.add(formData("login_password", "123")); // changed
auto content = 
postContent("https://scihub.copernicus.eu/dhus/login;, form);

writeln("Output:");
writeln(content);

Return error about login pass. So it's seems that I need to add 
BasicAuthentication method type. But how to add it?



Browser console show next: https://snag.gy/VXaq2R.jpg


Something like:

Request req;
req.authenticator = new BasicAuthentication("login", "password");


How to add authentificaion method to request?

2017-07-11 Thread Suliman via Digitalmars-d-learn
I am using dlang-requests. I need authentificate on 
https://scihub.copernicus.eu/dhus/login and than do some 
data-parsing.


MultipartForm form;
form.add(formData("login_username", "Suliman"));
form.add(formData("login_password", "123")); // changed
auto content = 
postContent("https://scihub.copernicus.eu/dhus/login;, form);

writeln("Output:");
writeln(content);

Return error about login pass. So it's seems that I need to add 
BasicAuthentication method type. But how to add it?



Browser console show next: https://snag.gy/VXaq2R.jpg


Re: Static array with parameter based size?

2017-07-11 Thread Dgame via Digitalmars-d-learn

On Tuesday, 11 July 2017 at 08:23:02 UTC, Miguel L wrote:

I need to create a non-dynamic array like this

void f(int x)
{
int[x] my_array;
...

this does not compile as x value needs to be known at compile 
time. The closest to this I can get is:


void f(int x)
{
int[] my_array;
my_array.length=x;

but I don't really need a dynamic array as length is not going 
to change inside f.


What is the best way to do this?

Thanks in advance

Another approach would be to use a template function:


void f(int x)()
{
int[x] array;
}

void main()
{
f!42;
}



Re: Static array with parameter based size?

2017-07-11 Thread ketmar via Digitalmars-d-learn

Miguel L wrote:


I need to create a non-dynamic array like this

void f(int x)
{
int[x] my_array;
...

this does not compile as x value needs to be known at compile time. The 
closest to this I can get is:


void f(int x)
{
int[] my_array;
my_array.length=x;

but I don't really need a dynamic array as length is not going to change 
inside f.


What is the best way to do this?

Thanks in advance


for simple cases you can use `alloca()`. it is fairly low-level, but does 
it's job.


but if your array is really big, or contains types with dtors, you'd better 
stick with `new` (or setting length). you can also put `scope(exit) delete 
my_array;` after declaration, so array will be destroyed on function exit. 
`delete` is... slightly deprecated ;-) (i.e. not recommented for wide use), 
but works, and will call dtors for you.


Static array with parameter based size?

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

I need to create a non-dynamic array like this

void f(int x)
{
int[x] my_array;
...

this does not compile as x value needs to be known at compile 
time. The closest to this I can get is:


void f(int x)
{
int[] my_array;
my_array.length=x;

but I don't really need a dynamic array as length is not going to 
change inside f.


What is the best way to do this?

Thanks in advance



Re: Why no offsetof for static struct?

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

On 07/10/2017 11:14 PM, FoxyBrown wrote:

auto GetStaticAddress(T)()
{
 mixin("auto p = cast(T*)"~__traits(allMembers, T)[0]~";");
 return p;
}


Returns the address of a struct's static members.


No, it returns the address of T's first member.

It's pretty obvious, the compiler seems to instantiate the static 
members simply as a sort of "singleton". They are laid out with the same 
relative offsets as the struct(which is obvious, as that is the most 
natural way). That is all that is needed to treat the memory the static 
variables use as the struct in which they are part of. No need to make 
it any more complex than that.


There may be cases where that happens, but it's not guaranteed. Here's 
an example where static members don't get stored together:



struct SA
{
static int x;
static immutable int y;
}

struct SB
{
static int x;
static immutable int y;
}

struct D
{
int x;
immutable int y;
}

const(void)*[] addressesOfMembers(alias thing)()
{
import std.meta: AliasSeq;

static if (is(thing)) alias T = thing;
else alias T = typeof(thing);

const(void)*[] addresses;
foreach (m; AliasSeq!(__traits(allMembers, T)))
{
addresses ~= &__traits(getMember, thing, m);
}
return addresses;
}

void main()
{
import std.stdio;
writeln("members of SA: ", addressesOfMembers!SA);
writeln("members of SB: ", addressesOfMembers!SB);

D d;
writeln("members of d:  ", addressesOfMembers!d);
}


Prints something like this (Ubuntu, x86-64):


members of SA: [7F7B2A294E90, 55EB7957FE94]
members of SB: [7F7B2A294E94, 55EB7957FE9C]
members of d:  [7FFDD1F2E4B8, 7FFDD1F2E4BC]


Note that SA's second member is stored far away from its first member. 
Same for SB. Also, SB's second member is stored between SA's members.


In contrast, d's members are packed together, because they're not static.


Re: Fiber based UI-Toolkit

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

On 2017-07-11 04:40, Gerald wrote:

Thanks for the link, I'm not active with .Net so I had to go look it up. 
Reminds me a lot of the way node.js works. If all your async activity is 
IO bound maybe it works fine and I'm wrong about this.



My past experience has been that it's challenging to determine the 
appropriate times to yield particularly with a lot of async activity 
happening. However with it baked into the framework and a simplified API 
maybe it becomes less of an issue.


I'll have to do more reading on it, again thanks for the pointer.


I'm not that familiar with .Net either but this async/await feature is 
spreading across languages: C++, JavaScript, .Net, Dart and possibly others.


As far as I understand it consists of two parts: coroutines (resumable 
functions) and asynchronous operations, usually IO. Any async function 
returns some form of future type. If you call that function, it will 
return immediately and let the execution continue. Now it's possible to 
do work that is independent of the result of the previous call. When you 
do need the result of the first call, you call "await" on the return 
value of that call, the future. If the result is ready, everything is 
fine and the execution continues. If the result is not ready, your 
function will suspend and the caller will continue the execution.


You don't need to do any explicit yielding due to the language and 
framework support. The only thing you need to determine is when you need 
the result of an aysnc function call.


--
/Jacob Carlborg


Re: Foreign threads in D code.

2017-07-11 Thread Biotronic via Digitalmars-d-learn

On Monday, 10 July 2017 at 20:03:32 UTC, Igor Shirkalin wrote:

Hello!

I have written some D code that I need to link to :C++ huge 
project. Let it be just one function that uses GC. The question 
is: if C++ code creates several threads and runs this :D 
function simultaneously, will GC work correctly?


p.s. Of course the druntime is initialized before it.

Igor Shirkalin


If DRuntime is not made aware of the thread's existence, the 
thread will not be stopped by the GC, and the GC might collect 
memory that the thread is referencing on the stack or in non-GC 
memory. Anything allocated by the GC would still be scanned.


To inform DRuntime about your thread, you should call 
thread_attachThis:


https://dlang.org/phobos/core_thread.html#.thread_attachThis

As pointed out in the documentation of thread_attachThis, you 
might also want to call rt_moduleTlsCtor, to run thread local 
static constructors. Depending on your usage, this might not be 
necessary.


--
  Biotronic