Re: this T / variadic template and interfaces

2020-10-26 Thread Jacob Carlborg via Digitalmars-d-learn

On Monday, 26 October 2020 at 11:14:47 UTC, frame wrote:

Is there any way to get this working? I know, I could use a 
known object to feed the arguments and use that instead - but I 
want to keep things simple as possible.


As Simen mentioned, templates cannot be virtual. But you don't 
need to use a template, you can use a regular variadic method 
[1]. It's a bit more clunky to work with than template variadic 
functions. Or if all the arguments will be of the same type, you 
can use type safe variadic functions [2], which are easier to 
work with.


[1] 
https://dlang.org/spec/function.html#d_style_variadic_functions
[2] 
https://dlang.org/spec/function.html#typesafe_variadic_functions


--
/Jacob Carlborg



Re: Template pattern delegate?

2020-10-26 Thread Jacob Carlborg via Digitalmars-d-learn

On Monday, 26 October 2020 at 00:56:26 UTC, frame wrote:

I see that your approach can handle functions and delegates but 
isn't that not equivalent like this template for a function?


auto myStuff(T)(T function() fn) {
try {
return fn();
}
catch (Exception e) {
//
}
}


You cannot pass a delegate to something that expects a function 
pointer.


I wonder if I could use such a template as static variant and 
the compiler just expands the code? Just thinking that using a 
function or delegate is an overhead. Maybe not a function but a 
delegate will allocate GC memory I think.


If you pass the delegate as a template parameter/alias parameter, 
it's more likely to be inlined:


auto myStuff(alias fn)() {
try return fn();
catch (Exception e) { }
}

myStuff!( { /* some code */ } );

--
/Jacob Carlborg




Re: Can we do compile time reading part of a file using import?

2020-10-26 Thread Jacob Carlborg via Digitalmars-d-learn

On Sunday, 25 October 2020 at 16:50:09 UTC, Jack wrote:

Which build tool are you refering to? an existing one or build 
one oneself to do this job?


It should work with any build tool that has hooks to execute 
arbitrary commands.


--
/Jacob Carlborg




Re: Two ways of receiving arrays on the C ABI

2020-10-25 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-10-20 02:16, Ali Çehreli wrote:

Everything works at least on Linux. Is this kosher, or am I using some 
internal knowledge?


Yes, you're using some internal knowledge. You cannot assume it works on 
any other platform or architecture. In theory, the D compiler could 
choose to change the ABI for passing D arrays and this would break. If 
fact, the ABI documentation [1] doesn't mention how a D array is passed. 
A different compiler could choose to pass it differently.


[1] https://dlang.org/spec/abi.html#arrays

--
/Jacob Carlborg


Re: Can we do compile time reading part of a file using import?

2020-10-25 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-10-23 18:42, data pulverizer wrote:

For me it's not make-or-break, it just something very useful and I think 
has clear use case. Please let me know if there are aspects or 
alternatives I am missing.


You could always have the build tool split up the file in multiple 
smaller files and read one of the smaller files with the import expression.


--
/Jacob Carlborg


Re: Druntime without pthreads?

2020-10-21 Thread Jacob Carlborg via Digitalmars-d-learn

On Tuesday, 20 October 2020 at 16:58:12 UTC, Severin Teona wrote:

Hi guys.

I have a curiosity, regarding [1] - I had encountered some 
"undefined reference" errors when trying to link the druntime 
(compiled for an embedded architecture) without some 
implementation of the POSIX thread calls (and other stuff too).


First, keep in mind that druntime and Phobos depends heavily on 
the C standard library, the Posix APIs, Windows APIs and other 
platform specific APIs. There's no list of what features or APIs 
need to be supported by a platform. There's no general concept of 
optional platform features, i.e. druntime will not automatically 
adopt if your platform doesn't support a specific feature (like 
threads). For example, on iOS (and related platforms) 
`std.process` is not supported (because you're not allowed to 
call `fork`). This is just hardcoded: if the platform is iOS, 
don't provide `std.process`.


What I'm saying, if you modify druntime to remove threads and 
locks, and resolve your undefined references, you might end up 
with new undefined references for other symbols.


My curiosity is what would change if I removed from the 
druntime everything that has to do with mutexes or threads. 
Would it be possible for the druntime to run and work properly 
on a microcontroller - where those concepts are not necessary? 
Could I just remove everything about synchronisation from the 
druntime, and classes or Garbage Collector to still work 
properly?


The garbage collector will probably work (if you remove the 
interaction with threads from it). Classes are a bit more 
complicated, they have a hidden monitor field [1]. There's also 
the concept of synchronized classes [2]. There's also the 
`synchronized` statement [3]. All these depend on 
mutex/monitors/locks in some form (I don't know exactly how the 
implementation works). Hopefully it should be fine as long as 
your code doesn't use the `synchronized` statement or 
synchronized classes. But all classes do come with a hidden 
monitor field.


[1] https://dlang.org/spec/abi.html#classes
[2] https://dlang.org/spec/class.html#synchronized-classes
[3] https://dlang.org/spec/statement.html#synchronized-statement

--
/Jacob Carlborg



Re: Escape this in pure members

2020-09-22 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-09-19 21:50, Per Nordlöw wrote:

On Saturday, 19 September 2020 at 18:48:31 UTC, Jacob Carlborg wrote:

A nested class seems to be able to escape the `this` reference:


Ahh, thanks.

I just realized that it can escape into other parameters without the 
`scope` qualifier?


This

class Bar
{
     void bar(scope Bar b) @safe pure
     {
     b = this;
     }
}

compiles but this

class Bar
{
     scope void bar(scope Bar b) @safe pure
     {
     b = this; // Error: scope variable `this` assigned to `b` with 
longer lifetime

     }
}


Hmm, why would `b` have longer lifetime? Isn't the lifetime of `b` 
throughout `bar`?


--
/Jacob Carlborg


Re: Escape this in pure members

2020-09-19 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-09-19 18:07, Per Nordlöw wrote:
If an aggregate member is pure but not scope when can it escape the 
`this` pointer?.


Only via return?


I'm not sure if returning the `this` pointer is considered escaping it. 
The caller already had access to it. Under the hood, the `this` pointer 
is just another argument passed to the function.



In the struct and class case?


A nested class seems to be able to escape the `this` reference:

class Foo
{
Bar b;

class Bar
{
void bar() pure
{
b = this;
}
}
}

--
/Jacob Carlborg


Re: Good repos to learn D

2020-09-19 Thread Jacob Carlborg via Digitalmars-d-learn

On Saturday, 19 September 2020 at 08:26:36 UTC, Imperatorn wrote:
What are some good examples of pretty large/medium size, good 
structured repos in D? I'm looking for examples to learn from


Thanks!


Here are some examples of large projects:

* DWT [1]. This is one of the largest D projects I'm aware of. 
It's a port from Java so it's structured like a Java project. I 
think it works pretty well for D projects as well. But it's not 
common to have the reverse domain name package structure like in 
Java. It's more common to have the top level package be named 
after the project.


* Mecca [2]. This one is not as large as DWT, but I think it 
nicely shows how to separate the platform specific code from the 
platform independent code. Instead of having `version` statements 
sprinkled all over the code most platform specific code is 
located in the `platform` packages. Then it provides a common 
interface that is used by the rest of the project.


* Ocean [3]. This one is quite large as well.

[1] https://github.com/d-widget-toolkit/dwt
[2] https://github.com/weka-io/mecca
[3] https://github.com/sociomantic-tsunami/ocean

--
/Jacob Carlborg


Re: DDoc generation

2020-09-19 Thread Jacob Carlborg via Digitalmars-d-learn
On Saturday, 19 September 2020 at 07:43:24 UTC, Russel Winder 
wrote:


Doesn't that then make the whole DDoc system fairly useless, 
despite it's use in Phobos?


If you use Dub, you can run `dub build -b ddox` and it will use 
Ddox to build the documentation. This will include an index page 
listing all modules. This will actually start a local web server 
to show the documentation. It's possible to generate 
documentation offline as well [1].


Or it should be pretty straightforward to write a simple script 
that iterates all D files and generates documentation. Then 
iterate all HTML files and output a simple index.html file.


[1] 
https://github.com/rejectedsoftware/ddox#generating-offline-documentation


--
/Jacob Carlborg



Re: DDoc generation

2020-09-19 Thread Jacob Carlborg via Digitalmars-d-learn
On Saturday, 19 September 2020 at 07:43:24 UTC, Russel Winder 
wrote:


Doesn't that then make the whole DDoc system fairly useless, 
despite it's use in Phobos?


Yes.  The problem is that most things in D are compared with C or 
C++. People are praising that the built-in support for unit tests 
and Ddoc are the best things that have happened since sliced 
bread. But if you compare with C or C++ the bar isn't very high.


--
/Jacob Carlborg


Re: Question about linker errors when using slices

2020-09-19 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-09-19 04:45, tspike wrote:
I’ve been using D for personal projects for almost a year now and I 
really love it. I recently ran across a linker error that I’m a little 
confused by. Consider the following files:


platform.d:

     module platform;

     import app;

     struct PlatformData
     {
     AppData a;
     }

     void main()
     {

     }

app.d:

     module app;

     struct AppData
     {
     //int* items;
     int[] items;
     }

If you only compile platform.d, the linker will complain about 
“undefined references.” This is true when using dmd and gdc, though 
platform.d compiles just fine when using ldc. But the file only fails to 
compile when the “items” member of AppData is a slice; if “items” is an 
int* platform.d will compile.


The linker spits the following:

     platform.o:(.data._D22TypeInfo_S3app7AppData6__initZ+0x30): 
undefined reference to `_D3app7AppData9__xtoHashFNbNeKxSQBeQBdZm'
     platform.o:(.data._D22TypeInfo_S3app7AppData6__initZ+0x38): 
undefined reference to `_D3app7AppData11__xopEqualsFKxSQBdQBcKxQjZb'


I was just wondering if anyone knows if this behavior is expected or if 
this is a compiler bug. Thank you in advance for your time!


You should compile both files. I'm guessing LDC might be doing some form 
of optimization to figure out that it doesn't need those symbols.



PS: I hope this is the right sub-forum for asking this sort of question!


Yes.

--
/Jacob Carlborg


Re: Proper way to exit with specific exit code?

2020-09-19 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-09-17 16:58, drathier wrote:

What's the proper way to exit with a specific exit code?

I found a bunch of old threads discussing this, making sure destructors 
run and the runtime terminates properly, all of which seemingly 
concluding that it's sad that there isn't a way to do this easily, but 
hopefully things have changed in the last 5-10 years and I'm just 
missing the obvious solution.


The proper way is:

int main()
{
return 42;
}

I highly recommend against trying to terminate the application using 
`exit` or any other way. Just let the control flow return back to the 
`main` function.


--
/Jacob Carlborg


Re: DDoc generation

2020-09-19 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-09-18 13:41, Russel Winder wrote:

Hi,

I am trying to get to grips with DDoc for documenting an application. Getting
the individual module HTML files seems to be the easy bit. The question is how
to get an index.html (or equivalent) so as to have an application level entry
point to the generated documentation.


There's no built-in support for that. You might want to look at some 
other doc generating tool if those support that.


--
/Jacob Carlborg


Re: get element index when using each!(x)

2020-09-18 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-09-17 05:16, Paul Backus wrote:

Worth knowing that the tuples you get from enumerate actually have named 
members, so you can write:


     s.enumerate.each!(x => writeln(x.index, ":", x.value));


It actually works out of the box for `each`:

s.each!((index, value) => writeln(index, ":", value));

https://dlang.org/phobos/std_algorithm_iteration.html#.each

--
/Jacob Carlborg


Re: Neater "not version (...)" ?

2020-09-18 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-09-16 21:04, Vladimirs Nordholm wrote:

Ah, I guess it boils down to this then. Doesn't really make it "neater", 
but thank you for the tip!


You only need to declare the enums ones.

--
/Jacob Carlborg


Re: Neater "not version (...)" ?

2020-09-16 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-09-16 19:53, Vladimirs Nordholm wrote:

Hello.

I wonder if there is a better way to compile something if the current 
operating system is _not_ a specific platform.


For example, I only want some code to compile if the operating system is 
not Windows. Currently I do this:


     version (Windows)
     {
     }
     else
     {
     // ... my code
     }

Is there a neater version of this, like `!version (Windows) { /+ ... my 
code +/ }` ?


The workaround for that is to define booleans for all versions and then 
use `static if`:


version (Windows)
enum windows = true;
else
enum windows = false;

static if (!windows)
{
// ... my code
}

--
/Jacob Carlborg


Re: tupleof seems to break encapsulation

2020-09-06 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-09-05 07:14, 60rntogo wrote:

I wouldn't dispute that it is useful, but that's besides the point. If I 
declare something private, it's usually because I want to preserve 
certain invariants and I want the compiler to provide a guarantee that I 
don't accidentally violate them. As it stands, the compiler cannot 
guarantee that if I use tupleof.


I don't really have an issue with read-only access to private fields 
(but arguments could be made against it) and then serialization would 
still be possible. However, if my struct is supposed to maintain 
invariants, then any attempt at deserialization that naively reads from 
a tuple without establishing these invariants should fail to compile.


I wouldn't mind if `tupleof` was not allowed in @safe code, which Walter 
mentions in one of the linked issues. Although it would be a breaking 
change.


Secondly, my serialization library, Orange [1], uses `tupleof` to read 
and write fields. It also supports before and after hooks for both 
serialization and deserialization. This allows to implement any 
invariants that are not covered by just restoring the fields. It also 
supports implementing a method that allows to take full control of the 
(de)serialization of a specific type.


Thirdly, you can do the same thing with pointer arithmetic. Although 
this is not allowed if @safe code.


[1] https://github.com/jacob-carlborg/orange

--
/Jacob Carlborg


Re: tupleof seems to break encapsulation

2020-09-04 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-09-04 12:16, 60rntogo wrote:

Consider the following code.

foo.d
---
module foo;

struct Foo
{
   private int i;
}
---

main.d
---
void main()
{
   import std.stdio;
   import foo;

   auto x = Foo();
   writeln(x);
   // ++x.i;
   ++x.tupleof[0];
   writeln(x);
}
---

As expected, the commented line does not compile. If I uncomment it, I 
get the error "no property i for type foo.Foo". However, the rest of the 
code compiles just fine and outputs:

---
Foo(0)
Foo(1)
---

This appears to defeat the purpose of declaring i private. What am I 
missing?


It's useful for serialization and, as you can see in your example, for 
debugging as well. `writeln` will print the values of the fields in a 
struct, even for private fields.


--
/Jacob Carlborg


Re: Install multiple executables with DUB

2020-09-03 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-09-03 14:41, glis-glis wrote:


Yes I already tried that, but I get the error

Error: only one main allowed. Previously found main at src/scripts/copy.d

Looks like DUB doesn't like multiple binaries?


Oh, multiple binaries, I missed that. You can try to add multiple 
configurations [1]. Or if you have executables depending on only one 
source file, you can use single-file packages [2].


Here are some real-world examples [3][4].

[1] https://dub.pm/package-format-sdl.html#configurations
[2] https://dub.pm/advanced_usage.html
[3] https://github.com/jacob-carlborg/dstep/blob/master/dub.json#L26
[4] 
https://github.com/d-widget-toolkit/dwt/blob/master/org.eclipse.swt.snippets/src/org/eclipse/swt/snippets/Snippet10.d


--
/Jacob Carlborg


Re: Install multiple executables with DUB

2020-09-03 Thread Jacob Carlborg via Digitalmars-d-learn

On Thursday, 3 September 2020 at 08:22:25 UTC, glis-glis wrote:

I usually would just write a makefile for that, but I thought 
I'd give DUB a go. Unfortunately, the DUB-documentation is a 
little thin and I cannot find a way to tell DUB
"compile all the files in the scripts folder and put the binary 
to the bin folder". How do I do that?


By default Dub will compile all files in the `source` or `src` 
directory and place the binary in the root directory of the 
project. If you want to override that you can use the following 
build settings `sourcePaths` or `sourceFiles` to override the 
source directory. To override the output directory you can use 
`targetPath` build setting. They are documented here [1][2].


[1] For the SDL format: 
https://dub.pm/package-format-sdl.html#build-settings
[2] For the JSON format: 
https://dub.pm/package-format-json.html#build-settings


--
/Jacob Carlborg


Re: Installing D on Fresh Windows 10 machine is a pain

2020-08-28 Thread Jacob Carlborg via Digitalmars-d-learn

On Friday, 28 August 2020 at 05:38:59 UTC, novice3 wrote:
DMD x86 on Windows have no dependencies, just unpack .zip and 
use.

It's a pitty, that DMD x64 depend on VS :(


It does not. If VS is not installed the MinGW provided libraries, 
which are bundled, will be used.


--
/Jacob Carlborg


Re: How does D's templated functions implementation differ from generics in C#/Java?

2020-08-08 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-08-07 23:03, aberba wrote:
Syntactically they look the same (although D's can do more things) so 
I'm trying to understand how why in D it's called template but in 
languages like C#/Java they're generics.



I guess I have fair understanding of D's code generation but isn't it 
same as what what is available in those languages too? How are the 
implementation different?


Objective-C recently added support for generics. It uses the same 
approach as Java, type erasure. Basically the only reason why this was 
added is to make the Swift APIs better and more type safe.


Swift also has quite an interesting implementation of generics. IIRC 
correctly it supports both a more Java like implementation where you 
only get one instantiation and a more D/C++ like implementation where 
the compiler generates one instantiation per type.


This is supposed to give the best of both worlds. Little binary bloat 
and high performance.


--
/Jacob Carlborg


Re: How does D's templated functions implementation differ from generics in C#/Java?

2020-08-08 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-08-07 23:39, H. S. Teoh wrote:


They are *very* different.

Java generics are based on "type erasure", i.e., at the syntactic level,
containers are parametrized with the element types, but at the
implementation level, the element types are merely "erased" and replaced
with Object (a top type of sorts). There is only one container
instantiation, which is shared across all parametrizations.  I don't
know exactly why this approach was chosen


I'm guessing a strong reason was to be backwards compatible with earlier 
versions of Java.


The type erasure is also most likely the reason why Java generic types 
don't accept primitive types. They need to be boxed, i.e. `int` need to 
be wrapped in an object of type `Integer`.


--
/Jacob Carlborg


Re: Invoking the compiler during runtime

2020-08-05 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-08-05 09:57, cy wrote:

Well, I did find this: 
https://dlang.org/blog/2017/08/01/a-dub-case-study-compiling-dmd-as-a-library/ 


That is more for using the frontend, not the backend for generating code.


But it's pretty advanced... probably just invoking dmd would be good...


You can start with that at least.

--
/Jacob Carlborg


Re: Using D within a rust codebase

2020-07-28 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-07-27 13:43, Ali Çehreli wrote:


They should be taken care of when the program is linked with a D compiler.


Just linking with a D compiler is not sufficient. There needs to be a D 
main function for the runtime to automatically be initialized. If you 
make the D code a bit more complicated, for example:


static this()
{
import std.stdio: writeln;
writeln("static this");
}

Then that won't be printed without a D main function or manually 
initializing the runtime.


The initial question was about linking D code into an already existing 
Rust code base. I don't think the first thing to try is to replace the 
Rust main function with a D main function.


--
/Jacob Carlborg


Re: Using D within a rust codebase

2020-07-27 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-07-27 03:03, Paul Backus wrote:


extern(C) void hello()
{
 import std.stdio: writeln;
 writeln("Hello from D!");
}


The D runtime needs to be initialized first [1]. Then it should be 
terminated as well [2].


[1] https://dlang.org/phobos/core_runtime.html#.rt_init
[2] https://dlang.org/phobos/core_runtime.html#.rt_term

--
/Jacob Carlborg


Re: Question about publishing a useful function I have written

2020-07-15 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-07-14 23:58, Cecil Ward wrote:

What’s the best way to publish a D routine ?


As others have already said, on GitHub. Then as a Dub package as well [1].

[1] https://code.dlang.org

--
/Jacob Carlborg


Re: misc questions about a DUB package

2020-07-15 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-07-15 04:20, 9il wrote:

No. Usually, a DUB package supports a range of C library version or just 
a fixes set of C API. The version behavior of the dub package is up to 
you. Usually, D API changes more frequently than the underlying C library.
If you support a specific version of the C API, I recommend adding the 
version of the C library as metadata:


0.0.1+5.3

In the above example "0.0.1" would be the version of the Dub package. 
"5.3" would be the version of the C API. The plus sign and anything 
after is ignored by Dub. See semantic versioning docs for more information:


https://semver.org

--
/Jacob Carlborg


Re: Bind C++ class to DLang : undefined reference to `Canvas::Foo()'

2020-07-15 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-07-14 05:33, Boris Carvajal wrote:

Can you try passing -D_GLIBCXX_USE_CXX11_ABI=0 to g++ and 
-version=_GLIBCXX_USE_CXX98_ABI to dmd.


That comes from: https://dlang.org/changelog/2.088.0.html#std_string

C++11 ABI is currently not supported.


I based on previous messages and the usage of Clang, I think zoujiaqing 
is using a Mac. On Mac libc++ is used. That above might not apply.


--
/Jacob Carlborg


Re: Choosing a non-default linker for dmd (via dub)

2020-07-15 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-07-12 18:36, Per Nordlöw wrote:

The line

dflags "-linker=gold" platform="linux-ldc" # use GNU gold linker

in dub.sdl

enables me to change linker for LDC.

Is it possible to choose a specific linker for DMD aswell in a similar way?

I only find the flag `-L` that sets flags but no linker executable.

One way is to link

     /usr/bin/ld

to either

     /usr/bin/ld.gold

or

     /usr/bin/ld.lld

but it would be nice to be able to do this from the dub.sdl or the 
command-line call to dub.


There's an environment variable "CC" that can be used to select which C 
compiler is used. Is there any equivalence for selecting the linker, 
"LD" perhaps?


--
/Jacob Carlborg


Re: App/lib config system

2020-07-09 Thread Jacob Carlborg via Digitalmars-d-learn

On Thursday, 9 July 2020 at 06:57:22 UTC, Kagamin wrote:
If you suspect there's a contradiction in requirements, you 
need to specify them with better precision.


What are the contradictions in the requirements? I don't see any.

--
/Jacob Carlborg


App/lib config system

2020-07-08 Thread Jacob Carlborg via Digitalmars-d-learn
I'm looking for a way to configure applications and libraries. 
I'm imagining a way for libraries to hook into a single point to 
provide the configuration parameters the library provides. These 
parameters can then be changed in one location from the user of 
the libraries (usually an application). My main requirement is 
that it should be possible to configure compile time values. I 
think the best way to explain what I'm looking for is with an 
example:


module log;

import config;

void log(Level level, string message)
{
static if (config.log.isEnabled)
{
if (config.log.level >= level)
writeln(message);
}
}

In the above example, the code would be part of the "log" 
library. The configuration parameters `config.log.isEnabled` and 
`config.log.level` can be changed by the application that is 
using the "log" library. `config.log.isEnabled` is a compile time 
value, that can only be changed at compile time. 
`config.log.level` is a runtime value that can be changed at 
runtime as well.


Here's a list of my ideal requirements:

* Should support both compile time and runtime config parameters
* Arbitrary libraries should be able to hook into config system 
to provide it with its config parameters

* There should be one place to change the config
* The "config file" should be a regular D module
* It should work with Dub. In the above example the "log" library 
and the application would be in separate Dub packages.


I've done some experiments and I have some pieces working, but 
have not been able to glue everything together. I don't mind if 
there are any dirty tricks behind the scenes but I would like it 
to be as easy as the above example to use it, if possible.


Does anyone have a system like this that is already available?

--
/Jacob Carlborg



Re: How can I make DMD stop on the first fatal error? (-Wfatal-errors)

2020-07-08 Thread Jacob Carlborg via Digitalmars-d-learn

On Wednesday, 8 July 2020 at 00:54:40 UTC, Marcone wrote:
How can I make DMD stop on the first fatal error like 
-Wfatal-errors on C++?


With the `-verrors=1` flag. You can specify exactly how many 
errors the compiler should emit before halting the compilation. 
Specify `0` for unlimited.


--
/Jacob Carlborg


Re: Construct an used-defined hash table container type from an AA-literal expression

2020-07-08 Thread Jacob Carlborg via Digitalmars-d-learn

On Tuesday, 7 July 2020 at 12:41:23 UTC, Per Nordlöw wrote:

What about construction and assignment from a static array of 
`Pair`'s? Wouldn't that be easier on the compiler?


I you refer to it wouldn't be using templates, then yes, I guess 
so.


--
/Jacob Carlborg



Re: Construct an used-defined hash table container type from an AA-literal expression

2020-07-06 Thread Jacob Carlborg via Digitalmars-d-learn

On Sunday, 5 July 2020 at 21:06:32 UTC, Per Nordlöw wrote:
Is there a way to construct a custom written hash-table 
container (struct) from an AA-literal expression?


I think your best bet is a tuple of pairs, because then you're 
not limited to compile time values, but it won't look pretty:


import std;

struct Pair
{
string key;
int value;
}

void main() @nogc
{
auto a = tuple(Pair("foo", 1), Pair("bar", 2));
}

--
/Jacob Carlborg


Re: Construct an used-defined hash table container type from an AA-literal expression

2020-07-06 Thread Jacob Carlborg via Digitalmars-d-learn

On Monday, 6 July 2020 at 01:43:43 UTC, user1234 wrote:


---
import std;

struct AA
{
void opIndexAssign(int v, string k) @nogc
{}
}

void main(string[] args) @nogc
{
AA myCustom;

enum literal = ["one":1, "two":2].stringof[1..$-1];
enum pairs   = literal.split(',').array;
static foreach (p; pairs)
{
myCustom[mixin(p.split(':')[0])] = 
mixin(p.split(':')[1]);

}
}
---


`static foreach` actual works for AA literals in `@nogc` 
functions. So there's no need complicate things with `.stringof`:


struct Foo
{
int a;
int b;
}

enum literal = ["one": Foo(1, 2), "two": Foo(3, 4)];

struct AA
{
void opIndexAssign(Foo value, string k) @nogc
{
}
}

void main() @nogc
{
AA aa;

static foreach (k, v; literal)
{
aa[k] = v;
}
}



Re: Construct an used-defined hash table container type from an AA-literal expression

2020-07-06 Thread Jacob Carlborg via Digitalmars-d-learn

On Monday, 6 July 2020 at 01:43:43 UTC, user1234 wrote:


Hereh we go ;)

---
import std;

struct AA
{
void opIndexAssign(int v, string k) @nogc
{}
}

void main(string[] args) @nogc
{
AA myCustom;

enum literal = ["one":1, "two":2].stringof[1..$-1];
enum pairs   = literal.split(',').array;
---


That split won't work if you have something more complicated, 
like struct values:


struct Foo
{
int a;
int b;
}

enum literal = ["one":Foo(1, 2), "two":Foo(3, 
4)].stringof[1..$-1];

enum pairs = literal.split(',').array;
static assert(pairs == 4);

--
/Jacob Carlborg


Re: Print only part of a stack trace

2020-07-01 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-07-01 19:44, Dennis wrote:
On assertion failure, the default error handler prints a stack trace 
that looks like this


[library functions]
[application functions]
[druntime start-up functions]

I'm only interested in application functions, the rest is noise.
I could easily filter unwanted lines out if I had the stack trace in 
string form, but I don't know how to obtain that. Is there a simple way 
to do this, or should I delve into Druntime internals?


Could `Runtime.traceHandler` [1] be that you're looking for?

[1] https://dlang.org/phobos/core_runtime.html#.Runtime.traceHandler

--
/Jacob Carlborg


Re: Calling C functions

2020-06-30 Thread Jacob Carlborg via Digitalmars-d-learn
On Tuesday, 30 June 2020 at 12:22:15 UTC, Steven Schveighoffer 
wrote:



(i.e. one cannot use extern(D) functions for C callbacks).


I don't think that's a big issue. Honestly, I don't think it's an 
issue at all.


BTW, the order of arguments is not the only thing. Variadic 
functions in D and C are completely different. I don't think it's 
possible to implement a C style variadic function with D linkage 
(the language doesn't provide a syntax for it).


There's also D specific types which C cannot handle (like arrays 
and delegates).


I'm sure there are other differences in the ABIs.

--
/Jacob Carlborg


Re: Calling C functions

2020-06-29 Thread Jacob Carlborg via Digitalmars-d-learn
On Monday, 29 June 2020 at 16:34:33 UTC, Steven Schveighoffer 
wrote:


Are you sure? On the ABI page [1] , it says "The extern (C) and 
extern (D) calling convention matches the C calling convention 
used by the supported C compiler on the host system."


In that case the documentation is wrong. Here's an example 
showing the differences:


$ cat foo.c
#include 

void foo(int a, int b)
{
printf("a=%d b=%d\n", a, b);
}
$ clang -c foo.c
$ cat main.d
pragma(mangle, "foo") extern (D) void foo_extern_d(int, int);
pragma(mangle, "foo") extern (C) void foo_extern_c(int, int);

void main()
{
foo_extern_d(1, 2);
foo_extern_c(1, 2);
}
$ dmd main.d foo.o
$ ./main
a=2 b=1
a=1 b=2

This is on macOS.

--
/Jacob Carlborg


Re: Calling C functions

2020-06-26 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-06-26 18:54, Denis wrote:


OK, now this makes sense.

I tested calling the same callback function directly from D: it compiled 
and worked correctly. So at least prefixing the callback function with 
`extern(C)` doesn't prevent the rest of the D program from calling it too.


No, of course not. How would you otherwise call your `cfunc` function 
from your original example ;)


--
/Jacob Carlborg


Re: Downloading files over TLS

2020-06-26 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-06-26 15:16, Adam D. Ruppe wrote:

Yeah, I've been wanting to change that and use the native apis for years 
but like I just haven't been able to figure out the documentation of them.


That would be nice.

That's the problem of everything Apple makes. Kinda drives me nuts 
trying to keep up with their endless churn and constantly Think 
Different campaigns.


Hehe, yeah.

https://docs.microsoft.com/en-us/windows/win32/winhttp/winhttp-sessions-overview 



I guess that is more middle level but it isn't too hard to use. I think 
there's a flat out url -> bytes function too but I don't remember what 
it is.


Regardless, the Windows functions may look familiar if you have done 
AJAX - that was based on an IE object which was based on the Windows API.


Thanks, I'll take a look.

--
/Jacob Carlborg


Re: Downloading files over TLS

2020-06-26 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-06-26 14:43, User wrote:

It is possible to statically link libcurl into your application. No need 
to use OpenSSL as libcurl can be built with SChannel.


That sounds good.

It looks like I remembered wrong. std.net.curl uses `dlopen` on libcurl, 
not OpenSSL. This might be less of an issue assuming libcurl is built 
with the platform provided TLS implementation. Just make sure it's 
possible to statically link libcurl, without using `dlopen`.


--
/Jacob Carlborg


Re: Downloading files over TLS

2020-06-26 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-06-26 14:41, Kagamin wrote:


Maybe just start wget or something like that?


The point was to avoid runtime dependencies.

Since you want the latest certificate storage, you intend to support 
only the latest system. Many root certificates will timeout now.


I didn't say the latest certificate storage. I said the platform 
provided. If the system provided certificate expires I guess a lot of 
things won't work. An alternative would be to both ship with a 
certificate and be able to use the system provided one and try both



https://docs.microsoft.com/en-us/windows/win32/winhttp/about-winhttp


I'll take a look, thanks.

--
/Jacob Carlborg


Re: Downloading files over TLS

2020-06-26 Thread Jacob Carlborg via Digitalmars-d-learn

On Friday, 26 June 2020 at 11:10:27 UTC, ikod wrote:


Hello,

re `requests` - it uses dlopen (and variants for OSX and 
Windows, see 
https://github.com/ikod/dlang-requests/blob/master/source/requests/ssl_adapter.d#L50). The reason for dlopen is simple - compatibility with both openssl ver 1.0 and 1.1 (which have incompatible interfaces). To solve this problem I expose common interface for Requests internal needs, and detect and use different underlying openssl interfaces depending on library version.


Oh, it's that bad. That's disappointing.

I'm sure it is possible to detect library version at build 
time, and then use static linking. It just require some time 
investment to find most acceptable solution on how to do this.


I'm using a script (written in D) in my tool, DStep [1][2], to 
identify which versions of libclang is available and to select 
between dynamic link (not using `dlopen`) and static linking of 
libclang. It works pretty well.


Re Windows - I'd be happy to use native SecureChannel but I 
have zero windows programming experience. I'm completely open 
for any help in this field.


I don't have much experience with programming on Windows either. 
macOS is my main platform.


Bottom line - problem with SSL/TLS libraries lies in 
incompatibility between platforms and even inside the single 
library.


Yes. I'm trying to identify the best solution, which ideally 
requires the least amount of work.


[1] 
https://github.com/jacob-carlborg/dstep/blob/master/configure.d
[2] 
https://github.com/jacob-carlborg/dstep/blob/master/dub.json#L34-L41


--
/Jacob Carlborg


Downloading files over TLS

2020-06-26 Thread Jacob Carlborg via Digitalmars-d-learn
Downloading files over TLS. This seems that it's something that 
should be quite simple to do. My high level goals are 
cross-platform and easy distribution. I don't need anything fancy 
just a simple API like this:


download("https://url.com;, "/local/file");

Because of these goals, I have a few requirements, which I don't 
think are unreasonable:


* Cross-platform (macOS, Linux, Windows, possible FreeBSD)

* Minimal runtime requirements (I don't mind a few compile time 
requirements). I also don't mind runtime requirements that are 
guaranteed to exist


* Ideally using the platform provided TLS implementation, or at 
least platform provided certificates (I've been bitten several 
times due to old certificates making request fail)


* On Linux I would really like to have a fully statically linked 
binary, this will make distribution easier


* Due to the previous requirement, I think using musl will be 
required. For most parts glibc works fine for static linking, but 
I think in the case of networking it does not work. The DNS 
lookup (or something like that) doesn't work with static linking


I think the main problem of all this is picking the right TLS 
implementation.


The obvious candidate is std.net.curl, but I'm going to explain 
why that is not ideal, at least not how it's currently 
implemented. std.net.curl relies on OpenSSL, which is deprecated 
on several platforms. On several platforms it's not the main, 
platform provided TLS implementation. As far as I know, it also 
provides its own certificates and doesn't rely on the ones 
provided by the platform.


I going to break down some alternatives per platform.

macOS:
* std.net.curl. Depends on libcurl and OpenSSL. OpenSSL has been 
deprecated on macOS for many years. In one wants to use OpenSSL 
anyway, one need to ship it with the binary (statically link it). 
For other problems, see above


* requests [1]. This is a potential better alternative than 
std.net.curl since it doesn't rely on libcurl. But, it still 
relies on OpenSSL, so it has the same problems as std.net.curl


* vibe.d [2]. Does not depend on libcurl, but does depend on 
OpenSSL. But, it also supports Botan, which is promising. I'll 
discuss Botan separately


* Hunt [3]. Same problem as the other ones, relies on OpenSSL

* Arsd [4]. Relies on OpenSSL

* SecureTransport [5]. This is an Apple specific library provided 
by the platform. It seems to more or less follow the same idea as 
OpenSSL, it's independent on the transport layer and works with 
BSD sockets. Initially this looks perfect, it's provided by the 
platform and uses certificates provided by the platform. The main 
problem is that it has been deprecated. It also only supports TLS 
up to version 1.2 and since it's deprecated, it's likely that it 
won't support any newer versions


* Network [6]. This is an Apple specific library provided by the 
platform. This is the recommend alternative to SecureTransport. 
The problem is that this is not just an alternative TLS 
implementation, it's a completely different alternative to BSD 
sockets. The API is completely different and will require some 
extra layers to to provide a cross-platform API. This means that 
I cannot use any of the existing library to just add TLS, it will 
be a completely different implementation, which might be ok. 
Another big problem is that it only available on macOS 10.14 and 
later. I have not decided yet if this is acceptable or not


* NSURLSession [7]. This is an  Apple specific Objective-C class, 
provided by the platform. It's higher level than the Network 
framework and is available on all versions of macOS. This will 
again require a some extra layers to hide the platform specific 
API. There's also a problem with LDC which has very limited 
support for Objective-C interoperability.


Linux:
As far as I know, OpenSSL (or some version of it, like LibreSSL) 
is what's provided by the platform. So I guess that has to be 
acceptable on Linux.


* std.net.curl. The main problem with std.net.curl on Linux is 
that it uses `dlopen` to load the TLS library. `dlopen` doesn't 
work for a statically linked executable. Side note, `dlopen` 
doesn't work on iOS (for other reasons) so it would be nice if 
this could be fixed


* requests. Seems to do that same as std.net.curl, uses `dlopen`

* For the other alternatives (mentioned in the macOS section), I 
haven't investigated if they use `dlopen` or not


Windows:
I don't know that much of this platform.

* std.net.curl and basically all other options already mentioned 
relies on OpenSSL, which is not provided by the platform


* SChannel. As far as I know, this the the platform provided 
implementation of TLS on Windows.


* Are there any high level APIs, like NSURLSession, on Windows 
that can be used to download files?


Botan:

This seems like a good candidate. It even exists a full D port of 
it [8].


* This is not used by any specific platform but it can use the 
platform provided 

Re: Calling C functions

2020-06-26 Thread Jacob Carlborg via Digitalmars-d-learn

On Friday, 26 June 2020 at 00:30:22 UTC, Denis wrote:

I have a two questions about calling C functions from D.

(1) When passing a D callback to a C function, is there a way 
to write the code without having to prefix the callback 
declaration with "extern(C)"?


It's not a big deal adding the prefix to the D function 
declaration. It just seems odd to me to prefix D code with 
"extern(C)". For example, the following code works:


  extern(C) void cfunc(void function(int));
  extern(C) void dcallback(int x) {...} <-- Why extern(C)?
  cfunc();

Can this be rewritten, dropping the prefix from the second 
line? If not, it would be helpful to know why "extern(C)" is 
needed here too.


No, it cannot be dropped. `extern(C)` is required because C and D 
are using different calling conventions (D functions are also 
mangled). For example, D (at least DMD and LDC) are passing the 
arguments to the function in reverse.


(2) Is there a way to restrict the invocation of a linked C 
function to one specific D function?


If the C header is defined in one of the core.stdc libraries, 
the import statement can either be global or inside a specific 
D function -- both work. In contrast, when the C function 
prototype is written directly into the D program (as above), 
the linker complains unless this declaration is made global. If 
it's possible to restrict the scope of the C function to just 
one D function, I'll take advantage.


For functions nested in a D language construct (class, struct, 
function) the compiler will always use the D mangling, instead of 
the C mangling. In theory it would be possible to workaround that 
by forcing the mangled name using `pragma(mangle)`, but for some 
reason the compiler doesn't allow `pragma(mangle)` inside a 
function body, on a nested function declaration.


You can wrap up everything in a struct, as follows:

struct printf
{
pragma(mangle, "printf") extern (C) private static int 
printf(in char*, ...);


static int opCall(Args...)(Args args)
{
return printf(args);
}
}

void main()
{
printf("asd\n".ptr);
}

The `printf` function can be called from anywhere within the 
module, but not outside the module.


--
/Jacob Carlborg


Re: How to correctly integrate D library to Swift/Obj-C mobile project?

2020-06-24 Thread Jacob Carlborg via Digitalmars-d-learn

On Monday, 22 June 2020 at 14:32:21 UTC, Anton wrote:
I have a static library (.a) compiled with LDC for iOS 
platform. But I can't figure out how to correctly connect it to 
the project and call its functions. I've already linked binary 
with library to the project but IDE still doesn't see its 
classes and methods. Do I need to do some additional 
configurations?


When you say "IDE", I'm going to assume you're referring to 
Xcode. Xcode has absolutely no support for D at all.


Since the Objective-C support in LDC is so limited I would 
recommend creating `extern(C)` functions in the D code, which 
forwards to your D functions (or have the functions being 
`extern(C)` to begin with). Then you need to have these 
declarations available in a C header file, either created by 
using the `-HC` flag or by manually writing the declarations.


--
/Jacob Carlborg


Re: How to correctly integrate D library to Swift/Obj-C mobile project?

2020-06-24 Thread Jacob Carlborg via Digitalmars-d-learn

On Monday, 22 June 2020 at 19:41:22 UTC, Vlad wrote:

Is it even possible to compile D for iOS and use it the same 
way as compiled C++ static library? (We do need a D runtime)


Yes, druntime/Phobos will need to be linked like any other static 
library.


--
/Jacob Carlborg



Re: Some questions about strings

2020-06-22 Thread Jacob Carlborg via Digitalmars-d-learn

On Monday, 22 June 2020 at 04:08:10 UTC, Denis wrote:

The terminating null character was one of the reasons I thought 
strings were different from char arrays. Now I know better.


String **literals** have a terminating null character, to help 
with integrating with C functions. But this null character will 
disappear when manipulating strings.


You cannot assume that a function parameter of type `string` will 
have a terminating null character, but calling `printf` with a 
string literal is fine:


printf("foobar\n"); // this will work since string literals have 
have a terminating null character


--
/Jacob Carlborg


Re: Dub Error Message "Invalid variable: DUB"

2020-06-07 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-06-07 11:24, Russel Winder wrote:

Hi,

Why on earth is Dub sending out this error message (Invalid variable: DUB) on
GitLab but not on Travis-CI or locally?

OK, that was slightly rhetorical, more reasonably, why is dub sending out this
message at all?


Dub is supposed to make an environment variable named "DUB" available to 
the build script. It should contain the path to the Dub executable. I 
guess that somehow fails. Might be some unexpected character in the path?


--
/Jacob Carlborg


Re: Objective C protocols

2020-05-17 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-05-17 11:32, John Colvin wrote:

On Saturday, 16 May 2020 at 19:14:51 UTC, John Colvin wrote:

What's the best way to implement an Objective C protocol in D?

I see mention here 
https://dlang.org/changelog/2.085.0.html#4_deprecated_objc_interfaces 
but it's not clear where things are these days.


It's the same these days. It's still not implemented.

Based on some experimentation, I'm starting to wonder do protocols 
actually have any runtime component in Objective C?


No, not really.

Because if I pass in  an extern(Objective-C) class with the right interface to a function 
expecting a protocol everything just works.


Yes, that works fine.

You can put the methods from the protocol directly in the class that 
implements them or in a base class. If you really want to have a 
specific type for the protocol you can use an abstract class to emulate 
an interface/protocol and cast your actual class to the abstract class:


extern (Objective-C)
abstract class Printer // the protocol
{
void print(int value) @selector("print:");
}

extern (Objective-C)
class Foo : NSObject
{
override static Foo alloc() @selector("alloc");
override Foo init() @selector("init");

void print(int value) @selector("print:")
{
writeln(value);
}
}

extern (Objective-C) void print(Printer);

void main()
{
auto foo = Foo.alloc.init;
print(cast(Printer) cast(void*) foo); // need to cast through void*
}

--
/Jacob Carlborg


Re: Get unknown symbol (struct, method, class) tagged with User Defined Attributes

2020-05-13 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-05-12 06:02, Steven Schveighoffer wrote:

If you want a list of ALL symbols that have the UDA in the application, 
that would require some form of runtime reflection (like Java). D has 
very limited support for runtime reflection. In D, you would use some 
form of registration to tell the system about your symbols.


I think it's possible to implement the `RTInfo` template in `object.d`. 
But that requires a custom druntime.


`RTInfo` is a template that is instantiated once for each type in the 
program.


--
/Jacob Carlborg


Re: D and Async I/O

2020-05-12 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-05-12 11:23, Russel Winder wrote:

As far as I can tell D has no futures… 


Future and async in vibe.d [1]. Future in Mecca [2].

[1] https://vibed.org/api/vibe.core.concurrency/async
[2] 
https://github.com/weka-io/mecca/blob/0593a35dd1a9978855d7db349fc1172f04cf8013/src/mecca/reactor/sync/future.d#L23


--
/Jacob Carlborg


Re: Error running concurrent process and storing results in array

2020-05-11 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-05-07 02:17, data pulverizer wrote:


What is the difference between -O2 and -O3 ldc2 compiler optimizations?


`--help` says -O2 is "Good optimizations" and -O3 "Aggressive 
optimizations". Not very specific.


--
/Jacob Carlborg


Re: D and Async I/O

2020-05-11 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-05-11 16:44, Russel Winder wrote:


Crickey, a third option. This wil increase my dithering! ;-)


Forth: Mecca [1] :)

[1] https://github.com/weka-io/mecca

--
/Jacob Carlborg


Re: Error running concurrent process and storing results in array

2020-05-06 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-05-06 12:23, data pulverizer wrote:


Yes, I'll do a blog or something on GitHub and link it.


It would be nice if you could get it published on the Dlang blog [1]. 
One usually get paid for that. Contact Mike Parker.


[1] https://blog.dlang.org

--
/Jacob Carlborg


Re: Retrieve the return type of the current function

2020-05-06 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-05-05 19:11, learner wrote:

On Tuesday, 5 May 2020 at 16:41:06 UTC, Adam D. Ruppe wrote:


typeof(return)


Thank you, that was indeed easy!

Is it possible to retrieve also the caller return type? Something like:


Yes, kind of:

void foo(string caller = __FUNCTION__)()
{
import std.traits : ReturnType;

alias R = ReturnType!(mixin(caller));
static assert(is(R == int));
}

int bar()
{
foo();
return 0;
}


--
/Jacob Carlborg


Re: Error running concurrent process and storing results in array

2020-05-06 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-05-06 06:04, Mathias LANG wrote:

In general, if you want to parallelize something, you should aim to have 
as many threads as you have cores.


That should be _logical_ cores. If the CPU supports hyper threading it 
can run two threads per core.


--
/Jacob Carlborg


Re: Error running concurrent process and storing results in array

2020-05-06 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-05-06 08:54, drug wrote:


Do you try `--fast-math` in ldc? Don't know if 05 use this flag


Try the following flags as well:

`-mcpu=native -flto=full -defaultlib=phobos2-ldc-lto,druntime-ldc-lto`

--
/Jacob Carlborg


Re: Error running concurrent process and storing results in array

2020-05-06 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-05-06 05:25, data pulverizer wrote:
I have been using std.parallelism and that has worked quite nicely but 
it is not fully utilising all the cpu resources in my computation


If you happen to be using macOS, I know that when std.parallelism checks 
how many cores the computer has, it checks physical cores instead of 
logical cores. That could be a reason, if you're running macOS.


--
/Jacob Carlborg


Re: DConf 2017 Videos

2020-04-25 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-04-24 22:24, matheus wrote:

Hi, please could someone tell me where can I find videos from DConf 2017?

I pretty sure I watched them on Youtube sometime ago, but I can't find 
anymore.


By the way, I'm looking from one video where someone shows some "C 
flaws" and how to D as Better C could solve that.


I think it was the second talk in this list: 
https://dconf.org/2017/schedule/


Any idea?


I have previously downloaded the DConf videos. I sent them to Mike for 
him to upload.


--
/Jacob Carlborg


Re: Array fill performance differences between for, foreach, slice

2020-04-01 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-03-31 23:30, data pulverizer wrote:


$ dmd fill.d && ./fill


You have not enabled optimizations. You should compile with `-O -release 
-inline` to enable all optimizations.


Without optimizations I get numbers like these:

Slice: Mean time(usecs): 92.91, Standard Deviation: 49.8002
Foreach: Mean time(usecs): 183.95, Standard Deviation: 30.749
For: Mean time(usecs): 239.74, Standard Deviation: 30.753

With optimizations turned on I get quite varying results:

Slice: Mean time(usecs): 96.84, Standard Deviation: 52.5676
Foreach: Mean time(usecs): 95.84, Standard Deviation: 21.9244
For: Mean time(usecs): 106.73, Standard Deviation: 31.2545

Slice: Mean time(usecs): 192.03, Standard Deviation: 115.971
Foreach: Mean time(usecs): 177.06, Standard Deviation: 128.012
For: Mean time(usecs): 89.14, Standard Deviation: 25.681

Slice: Mean time(usecs): 97.74, Standard Deviation: 53.2058
Foreach: Mean time(usecs): 79.72, Standard Deviation: 11.0088
For: Mean time(usecs): 80.54, Standard Deviation: 12.06

I you care about performance you should really compile using LDC (with 
`-O5 -release -flto=full -defaultlib=phobos2-ldc-lto,druntime-ldc-lto`), 
which usually produces much better code:


Slice: Mean time(usecs): 50.58, Standard Deviation: 46.2621
Foreach: Mean time(usecs): 53.92, Standard Deviation: 19.8039
For: Mean time(usecs): 39.89, Standard Deviation: 7.80041

Slice: Mean time(usecs): 76.62, Standard Deviation: 73.0014
Foreach: Mean time(usecs): 49.63, Standard Deviation: 24.5672
For: Mean time(usecs): 40.02, Standard Deviation: 7.67388

--
/Jacob Carlborg


Re: A question about C++ interop

2020-03-28 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-03-27 20:17, YD wrote:

Hi, I have a C++ header file which looks like

     class A {
     public:
     static A *create();
     virtual int f() const = 0;
     };

And there is a C++ library file which provides the implementation, so 
that if I write a C++ program and call


     auto *p = A::create();
     std::cout << p->f() << '\n';

It will work.

Now I want to interface to this C++ library through D, and I wrote

     module test;

     import std.stdio;

     extern(C++) {
     class A {
     static A *create();
     abstract int f() const;
     }
     }

     void main() {
     auto p = A.create();
     writeln(p.f());
     }

This program will compile and link, but it core dumps at the call to f().

If I wrap up the C++ interface into a C interface (using a void *), and 
interface to the wrapped-up C library through D, it will work fine.


So what am I doing wrong here? Thanks!


Classes in D are always passed by reference. Try dropping the pointer in 
the `create` method:


static A create();

--
/Jacob Carlborg


Re: Best way to learn 2d games with D?

2020-03-16 Thread Jacob Carlborg via Digitalmars-d-learn
On Sunday, 15 March 2020 at 17:58:58 UTC, Steven Schveighoffer 
wrote:
I want to try and learn how to write 2d games. I'd prefer to do 
it with D.


I've found a ton of tutorials on learning 2d gaming with other 
languages. Is there a place to look that uses D for learning? 
Should I just start with another language and then migrate to D 
later? Anyone recommend any specific tutorial/book?


You can have a look at the SpriteKit framework [1]. Although it 
will only work on Apple’s platforms.


[1] https://developer.apple.com/spritekit/

—
/Jacob Carlborg


Re: Typescript with vibe.d

2020-03-10 Thread Jacob Carlborg via Digitalmars-d-learn

On Monday, 9 March 2020 at 09:42:16 UTC, GreatSam4sure wrote:
I want to know if it is possible to use typescript with the 
vibe.d since typescript is a superset of javascript. I will 
appreciate any example if it is possible


There's a Diet filter for TypeScript here [1], but it hasn't been 
updated since 2015.


[1] https://code.dlang.org/packages/diet-typescript

--
/Jacob Carlborg


Re: dscanner and ref parameters

2020-02-23 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-02-23 13:28, mark wrote:

Just realised that the arg is 'out' not 'ref'; don't know if that makes 
a difference to dscanner. Anyway, I've made a bug report: 
https://github.com/dlang-community/D-Scanner/issues/793


Same idea applies. dscanner should look at the signature. In the case of 
`out`, the compiler will also set the value of the argument to its .init 
value before calling the function.


--
/Jacob Carlborg


Re: dscanner and ref parameters

2020-02-23 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-02-23 10:03, mark wrote:

Then this would not only help dscanner, but also make it clear to 
programmers that the argument could be modified.


It's not necessary for dscanner. It should look at the signature of 
`getKeyval` to see that it takes an argument by `ref`.


--
/Jacob Carlborg


Re: Fastest linker on Mac OS X

2020-02-23 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-02-22 15:45, Per Nordlöw wrote:

What's the fastest linker to use when building using dmd or ldc on Mac?


There's only one linker that works properly, the official one, ld64. The 
LLVM LLD linker works in some cases but are missing some features. Some 
of the missing features are required by LDC, for example.


--
/Jacob Carlborg


Re: Porting D to custom OS

2020-02-23 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-02-22 20:30, IGotD- wrote:

That's sound like a start. Is there some kind of automation behind this 
based on the target triple (-mtriple) or just some kind of hardcoded 
default versions identifiers somewhere in the source code?


Have a look at [1] for a recent example.

[1] 
https://github.com/ldc-developers/ldc/pull/3288/commits/b9c284537a8392a5348fa32d36260595c66997f1


--
/Jacob Carlborg


Re: CTFE, string mixins & code generation

2020-01-24 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-01-24 19:43, H. S. Teoh wrote:


(enums cannot take AA's or
class objects as values, also, once assigned they are immutable).


AA enums work. Class objects kind of work. One can use static 
const/immutable instead. The following snippet compiles:


class A
{
int a = 3;
}

const bar = new A;
enum a = bar.a;

enum foo = [1:2];

void main()
{
}

--
/Jacob Carlborg


Re: Lexicographic comparison of arrays (of chars)

2020-01-22 Thread Jacob Carlborg via Digitalmars-d-learn

On Wednesday, 22 January 2020 at 14:50:01 UTC, Per Nordlöw wrote:


Will that incur an extra runtime cost compared to __cmp?


I haven't looked at how `__cmp` is implemented but I would guess 
there's some extra overhead. Need to get type info and then there 
will be several virtual method calls involved. Seems to be one of 
the initial call to `compare` and then one for each element of 
the array.


BTW, why don't you implement `opCmp` with the built-in comparison 
operators. Those are going to get lower to a call to `__cmp`. 
Something like this:


int opCmp()(const scope typeof(this) that) const @nogc
{
auto a = this[];
auto b = that[];
return a < b ? -1 : (a > b);
}

--
/Jacob Carlborg




Re: Lexicographic comparison of arrays (of chars)

2020-01-22 Thread Jacob Carlborg via Digitalmars-d-learn

On Wednesday, 22 January 2020 at 08:44:15 UTC, Per Nordlöw wrote:


I just found

import core.internal.array.comparison : __cmp;

I presume that is a better alternative if Phobos' independence 
is desired.


That looks like it's for internal use. There is a `compare` 
method in the `TypeInfo` of each type.


https://github.com/dlang/druntime/blob/2fa694319da397d72ab09cb336f3d588107278c1/src/object.d#L541

--
/Jacob Carlborg



Re: Get memory used by current process at specific point in time

2020-01-15 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-01-15 19:45, Chris Katko wrote:

Still, some internal instrumentation would be nice. But I'm not aware of 
any.


There are some runtime flags that can be passed to the executable when 
running it to get some info about the GC. Of course these are not 
documented (except perhaps in the changelog). I'm too lazy to try to 
find them now.


--
/Jacob Carlborg


Re: Get memory used by current process at specific point in time

2020-01-13 Thread Jacob Carlborg via Digitalmars-d-learn

On 2020-01-12 14:58, Per Nordlöw wrote:
Is there a druntime/phobos function for getting the amount of memory 
(both, stack, malloc, and GC) being used by the current process?


I don't think so. But if you're on macOS you can use Instruments 
(shipped with Xcode) and pick the Allocations template.


--
/Jacob Carlborg


Re: Template mixin / unresolved external / scope problem?

2019-11-28 Thread Jacob Carlborg via Digitalmars-d-learn

On 2019-11-28 16:40, Robert M. Münch wrote:

I have:

a.d:
extern (C) void myFuncA();

void myFuncB() {
 myFuncA();
}

b.d:
public import a;

mixin template MYFUNCA() {
 extern (C) void myFuncA() {...}
}

c.d:
import b;

mixin MYFUNCA;
...further code...


Compiling such a structure gives me an unresolved external in a.d/myFuncB

I assume this is because the mixin get's it's own scope. Is this 
correct? How can I solve such a setup?


Are you using the latest version, 2.089.0? It might be fixed in that 
version [1].


[1] https://dlang.org/changelog/2.089.0.html#mixin_template_mangling

--
/Jacob Carlborg


Re: Leak-detection of references to scoped class instances

2019-11-25 Thread Jacob Carlborg via Digitalmars-d-learn

On Sunday, 24 November 2019 at 21:49:19 UTC, Per Nordlöw wrote:
I guess we need a builtin language qualifier for scoped classes 
for that to work, right?


We have that:

scope a = new Object;

—
/Jacob Carlborg



Re: dmd memory usage

2019-11-24 Thread Jacob Carlborg via Digitalmars-d-learn

On 2019-11-18 01:20, Steven Schveighoffer wrote:
I'm fighting some out of memory problems using DMD and some 
super-template heavy code.


I have ideas on how to improve the situation, but it involves 
redesigning a large portion of the design. I want to do it 
incrementally, but I need to see things improving.


Is there a straightforward way to figure out how much memory the 
compiler uses during compilation? I though maybe /usr/bin/time, but I 
feel like I don't trust the output to be the true max resident size to 
be what I'm looking for (or that it's 100% accurate). Is there a 
sure-fire way to have DMD print it's footprint?


You can also try the memory profiler in Instruments (shipped with Xcode).

--
/Jacob Carlborg


Re: equivalent of typeid(Class).name at compile-time

2019-11-22 Thread Jacob Carlborg via Digitalmars-d-learn
On Thursday, 21 November 2019 at 20:44:19 UTC, Steven 
Schveighoffer wrote:
I thought I could do typeid(Class).name to get the class name 
that will be returned at runtime if you did 
typeid(instance).name. But it's not accessible at compile-time.


What compile-time string should I use for instance in a 
constructed switch statement? I'm trying to implement 
serialization and deserialization of classes, but I really 
would like to avoid using a class enum if possible, since the 
type id is already there and generated by the compiler.


I solved that by storing the class info as the key in an 
associative array [1]. But it looks like Adam's solution will 
work as well.


If you ideas, you can always have a look at Orange.

[1] 
https://github.com/jacob-carlborg/orange/blob/90f1dbb0097ba4a319805bfb7d109f7038418ac6/orange/serialization/Serializer.d#L241-L262


Re: How to get child class Type and members from parent class?

2019-11-20 Thread Jacob Carlborg via Digitalmars-d-learn

On Wednesday, 20 November 2019 at 10:05:11 UTC, zoujiaqing wrote:

import std.stdio;


class A
{
this(T)(T t)
{

}

void write()
{
T _this = cast(T) this;
writeln(this.v);
}
}

class B : A
{
string v = "hello";
}

void main()
{
auto b = new B;

writeln(b.write()); // print hello
}


You can use a template this parameter [1], like this:

import std.stdio;

class A
{
void write(this T)()
{
T self = cast(T) this;
writeln(self.v);
}
}

class B : A
{
string v = "hello";
}

void main()
{
auto b = new B;
b.write();
}

[1] https://dlang.org/spec/template.html#template_this_parameter

--
/Jacob Carlborg


Re: dmd memory usage

2019-11-18 Thread Jacob Carlborg via Digitalmars-d-learn
On Monday, 18 November 2019 at 15:31:02 UTC, Steven Schveighoffer 
wrote:
I don't think this will work for me, as this isn't CTFE, and 
I'm assuming the instantiated templates won't be collected 
because they stay referenced for the whole program.


You could also combine that flag with the GC profiling flags.

—
/Jacob Carlborg


Re: dmd memory usage

2019-11-18 Thread Jacob Carlborg via Digitalmars-d-learn
On Monday, 18 November 2019 at 00:20:12 UTC, Steven Schveighoffer 
wrote:
I'm fighting some out of memory problems using DMD and some 
super-template heavy code.


Try to enable the GC using the `-lowmem` flag [1].

[1] https://dlang.org/changelog/2.086.0.html#lowmem

—
/Jacob Carlborg




Re: Translating Java into D

2019-11-16 Thread Jacob Carlborg via Digitalmars-d-learn

On 2019-11-14 20:50, NonNull wrote:
Greetings, Java seems to be almost a subset of D in various ways. Has 
there been any work done to automatically translate Java source into D?


Yes, I'm working on a tool, JPort [1], for automatically translating 
Java to D. It's not done yet and there's been a couple of years now 
since I last worked on the project.


[1] https://github.com/d-widget-toolkit/jport/tree/dev

--
/Jacob Carlborg


Re: Translating Java into D

2019-11-16 Thread Jacob Carlborg via Digitalmars-d-learn

On 2019-11-16 08:13, GreatSam4sure wrote:

I am of the opinion that D is much more powerful than Java since I am 
familiar with the language to some extent. I am even to start a GUI app 
in java due to the fact I have no find a GUI toolkit in D that meet all 
my need.


There's DWT [1], which is a port of the Eclipse SWT Java library.

[1] https://github.com/d-widget-toolkit/dwt

--
/Jacob Carlborg


Re: is the runtime implemented in betterC?

2019-11-09 Thread Jacob Carlborg via Digitalmars-d-learn

On 2019-11-08 16:25, dangbinghoo wrote:

hmm, if runtime is implemented in regular D, how could the regular D 
code depends on regular D runtime be compiled when we doesn't have a D 
runtime even exists? thinking thant we just have xtensa-llvm, and 
building ldc for xtensa CPU,  the runtime will simply just not compiled.


it's an egg-chicken problem?


One needs to be a bit careful. For example, to not use the garbage 
collector before it's initialized.


--
/Jacob Carlborg


Re: Which is the active fork in DFL gui library ?

2019-11-04 Thread Jacob Carlborg via Digitalmars-d-learn

On 2019-11-03 17:48, Vinod K Chandran wrote:


@Jesse Phillips,
Thank you for the reply.  Does DWT is built upon Java's SWT ? 


Yes. It's a full translation of the Java code to D. No JNI, JVM or Java 
or remains.



I heard that SWT is somewhat slower in windows.


I don't know if that's the case. Also I don't know if that's related to 
Java/JVM. And I don't know how SWT and DWT compares in speed.


Anyhow, what about the easiness 
of DWT ?


There's no GUI builder for DWT, if you're interested in that. In theory 
you could use one for SWT and translate the Java code to D, but that 
might be more troublesome.


Actually, i just want to make GUI for Windows only. I dont need 
a cross platform GUI.


DWT works on Windows and Linux. But you don't need to compile it for 
Linux if you don't want to.


--
/Jacob Carlborg


Re: Running unittests of a module with -betterC

2019-10-30 Thread Jacob Carlborg via Digitalmars-d-learn

On 2019-10-30 16:09, jmh530 wrote:


I feel like this should be added into the compiler so that it just works.


This will only run the unit tests in the current modules. The standard 
way of running the unit tests will run the unit tests in all modules.


--
/Jacob Carlborg


Re: Read Once then reset/init value?

2019-10-30 Thread Jacob Carlborg via Digitalmars-d-learn

On 2019-10-30 00:28, Simen Kjærås wrote:


Something like this?

T readOnce(T)(ref T value) {
     auto tmp = value;
     value = T.init;
     return tmp;
} unittest {
     int i = 3;
     assert(i.readOnce == 3);
     assert(i == 0);
}


Perhaps better to encapsulate it in a struct to avoid someone accessing 
the value directly.


--
/Jacob Carlborg


Re: PHP to D Conversion

2019-10-18 Thread Jacob Carlborg via Digitalmars-d-learn

On Friday, 18 October 2019 at 06:22:33 UTC, Vino wrote:

Hi All,

  Request your help in converting a PHP code to D equivalent 
code


PHP Code:
class avmtest {
private $con;

function __construct() {
global $config;
$this->con = new mysqli(test.srv.com:3910, 
testusr, #, test);
if($this->con->connect_errno) { die("Connection 
Failed.\n"); }

}

function getHostname() {
$qdata = $this->con->prepare("SELECT host_name 
FROM hosts_coll");

$qdata->execute();
$qdata->bind_result($host);
while($qdata->fetch()) {
$data[] = array("HostName" => $host);
}
$sdata->close();
return $data;
}
}

D Code:
module avm.test;

import mysql;
import std.array : array;
import std.conv;
import std.variant;

class avmtest
{
private conn;

auto avmconnect()
{
	auto connectionStr = 
"host=test.srv.com;port=3910;user=testusr;pwd=#;db=test";

Connection conn = new Connection(connectionStr);
scope(exit) conn.close();
}

auto getHostname()
{
	  ResultRange qdata = conn.query("SELECT host_name FROM 
`hosts_coll`");

  Row row = qdata.front;
  Variant h = row[0];
  qdata.close();
  return h.to!string;
}
}

Error: Error: no identifier for declarator conn


The instance variable in the D code, `conn`,  doesn't have a 
type. I guess the type should be `Connection`. In the D version 
of `avmconnect` you're declaring a local variable named `conn` 
instead of referring to the instance variable.


--
/Jacob Carlborg




Re: Uninstalling DMG file

2019-10-16 Thread Jacob Carlborg via Digitalmars-d-learn

On 2019-10-16 05:30, Joel wrote:


Everything seems to be working again - yay!


Great. If you see a lot of warnings when linking, I have a PR for that [1].

[1] https://github.com/dlang/dmd/pull/10476

--
/Jacob Carlborg


Re: A proper WAT moment

2019-10-16 Thread Jacob Carlborg via Digitalmars-d-learn

On 2019-10-15 09:06, John Colvin wrote:

And all the other ones in my example that access members without an 
instance that also compile?


There's something pretty strange about the rules here.


The thing is that it should be possible to access a non-static member 
without an instance because it's possible to manually construct a delegate:


class S
{
int a;
int e() @property { return a; }
}

void foo()
{
int function() f =  // this compiles
int delegate() dg;
S s;
dg.ptr = 
dg.funcptr = f;
}

struct C
{
void bar()
{
int function() f =  // this fails for some reason but 
should compile

}
}

So the expression `S.e` should compile, because it can be part of a 
large expression, i.e. ``, which should compile.


The strange thing is that it fails to compile inside `C`. But if `bar` 
is changed to a static method it compiles again.


--
/Jacob Carlborg


Re: Undefined symbol: _dyld_enumerate_tlv_storage (OSX)

2019-10-14 Thread Jacob Carlborg via Digitalmars-d-learn

On 2019-10-14 09:29, Robert M. Münch wrote:


=> nm /usr/lib/system/libdyld.dylib | grep _dyld_enumerate_tlv_storage
00017eca T _dyld_enumerate_tlv_storage


Strange, the output shows that the symbol is present.

--
/Jacob Carlborg


Re: Undefined symbol: _dyld_enumerate_tlv_storage (OSX)

2019-10-14 Thread Jacob Carlborg via Digitalmars-d-learn

On 2019-10-14 07:36, Joel wrote:


I use Home Brew (brew upgrade dmd, and brew upgrade dub)
Brew is only up to 2.087.1 at the moment - John Colvin seems to be the 
man that mantains dmd with brew.


You can use DVM [1] to install the latest version of DMD.

[1] https://github.com/jacob-carlborg/dvm

--
/Jacob Carlborg


Re: Undefined symbol: _dyld_enumerate_tlv_storage (OSX)

2019-10-11 Thread Jacob Carlborg via Digitalmars-d-learn

On 2019-10-11 18:48, Robert M. Münch wrote:

On 2019-10-10 18:31:25 +, Daniel Kozak said:


What dmd version?


I think I had an older one like 2.085 or so. I updated to 2.088 and it 
now seems to work.



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


I'm on OSX 10.14.6, so this might not be directly related to Catalina 
but maybe more to the XCode Version installed:



| => xcrun --show-sdk-version

10.15


So, it's possible to run 10.14 with SDK version 10.15 which seems to 
trigger the problem.
No, I don't think that's the problem. I have the same setup and I don't 
have this problem.


What result do you get if you run the following command:

nm /usr/lib/system/libdyld.dylib | grep _dyld_enumerate_tlv_storage

--
/Jacob Carlborg


Re: Undefined symbol: _dyld_enumerate_tlv_storage (OSX)

2019-10-11 Thread Jacob Carlborg via Digitalmars-d-learn

On 2019-10-10 20:12, Robert M. Münch wrote:

I have two project I want to compile and both times get this error:

Undefined symbols for architecture x86_64:
  "_dyld_enumerate_tlv_storage", referenced from:
  __d_dyld_getTLSRange in libphobos2.a(osx_tls.o)

I'm wondering where this comes from as I didn't see it in the past. Any 
idea?




Any D application needs to be compiled with DMD 2.087.1 or later or the 
corresponding version of LDC to be able to run on macOS Catalina. That 
includes DMD itself. The oldest version of DMD that runs on Catalina is 
2.088.0, since any given version of DMD is compiled with the previous 
version.


That means that all D applications out there for macOS needs to be 
recompiled.


--
/Jacob Carlborg


Re: Packaging and Distributing Dlang Applications with GtkD Dependency?

2019-09-27 Thread Jacob Carlborg via Digitalmars-d-learn
On Wednesday, 25 September 2019 at 11:46:04 UTC, Ron Tarrant 
wrote:

Hi y'all,

I've been Googling how to do this, but coming up with nothing 
definitive. Are there any articles for how to do this for:


Windows?
Linux?
other UNIX-alike OSs?


For macOS you should distribute a GUI application for end users 
as an application bundle [1]. That's basically a directory 
containing a specific structure. Any dependencies and resources 
like libraries (GTK), images and so on should be bundled inside 
the application bundle. Then package the application bundle 
inside an archive, ideally a Disk Image (DMG) [2]. The 
application would be completely self contained and the user can 
install it by dragging it to the Application directory.


There might be some specific documentation how to bundle a GTK 
application on macOS. I found this [3], don't know if it's good 
or not.


Ideally the application should be distributed on the Mac App 
Store. But that requires a developer account that costs money. It 
also has some restrictions that distribution outside of the Mac 
App Store doesn't have. If you cannot distribute using the Mac 
App Store the next best thing is to notarize the application 
(also requires a paid developer account, as far as I can see) 
before distributing it. Otherwise the user will get a dialog 
complaining that the application is from an unknown developer and 
the user need to explicitly go into System Preferences to allow 
it.


[1] 
https://developer.apple.com/library/archive/documentation/CoreFoundation/Conceptual/CFBundles/BundleTypes/BundleTypes.html#//apple_ref/doc/uid/1123i-CH101-SW1


[2] https://en.wikipedia.org/wiki/Apple_Disk_Image
[3] https://gitlab.gnome.org/GNOME/gtk-mac-bundler

--
/Jacob Carlborg


Re: Deprecation message sources

2019-09-18 Thread Jacob Carlborg via Digitalmars-d-learn

On 2019-09-17 22:55, Johan Engelen wrote:


Wow. How come this is not caught by the CI testing?


That issue seems to be because "writeln" is printing "type", which is an 
enum. For enums, "writeln" prints the actual name of the enum member and 
not the value. It seems it extracts the names of all enum members and 
this particular enum contains deprecated members.


--
/Jacob Carlborg


Re: C++ vs D: Default param values and struct to array casting

2019-09-07 Thread Jacob Carlborg via Digitalmars-d-learn

On 2019-09-06 11:14, Andrew Edwards wrote:

C++ allows the for following:

struct Demo
{
 float a, b, c, d;
 Demo() { a = b = c = d = 0.0f; }
 Demo(float _a, float _b, float _c, float _d) {
     a = _a;
     b = _b;
     c = _c;
     d = _d;
 }
 float  operator[] (size_t i) const { return ()[i]; } //[3]
 float& operator[] (size_t i) { return ()[i]; } //[4]
}

void fun(float col[3])
{
 // do fun stuff
}

void moreFun(const Demo& d = Demo(0.1f, 0.3f, 7.5f, 1.5f)) // [1]
{
 // you guessed it... more fun stuff
}

int main(int argv, const char** argc)
{
 Demo inst = Demo(0.1f, 0.3f, 7.5f, 1.5f);
 fun((float*)); // [2]
 moreFun();
 return 0;
}

I'm seeking some pointers on how to define these in D so that I can 
instantiate them in D while still linking to the associated C++ library 
or object file for the implementation. The main points of contention are 
at [1] and [2] because I have no idea how to accomplish these.  I assume 
that I can accomplish [3] and [4] with opIndex() and opIndexAssign(), 
however I'm not understanding the slicing of the memory address at the 
first member variable. I know that by indexing the memory address at the 
member variable we are able treat the struct as an array but i do not 
understand how to implement it in D.


In D you can use the built-in property `.tupleof` [1], available for 
structs and classes. That will give you a tuple, not an array. To get an 
array you can just wrap it in square brackets:


Demo inst = Demo(0.1f, 0.3f, 7.5f, 1.5f);
auto tuple = inst.tupleof; // "tuple" is a tuple
auto arr = [tuple];
static assert(is(typeof(arr) == float[]));

Converting the tuple to an array like that only works then all of the 
elements of the tuple has the same type.


Here's an example:

struct Test
{
float a, b, c, d;

float opIndex(size_t i)
in(i >= 0 && i <= 3)
{
return [this.tupleof][i];
}

float get(size_t i)()
{
return this.tupleof[i];
}
}

void main()
{
auto t = Test(1, 2, 3, 4);
assert(t[3] == 4);

assert(t.get!3 == 4);
}

If you can provide the index at compile time you don't need to create an 
array of the the tuple. The "get" method shows that technique. 
Unfortunately "opIndex" cannot take the index as a template parameter. 
Here's the runnable version [2].


[1] https://dlang.org/spec/struct.html#struct_instance_properties
[2] https://run.dlang.io/is/7QYljZ

--
/Jacob Carlborg


Re: Why are extern(C/C++) definitions and references mangled differently in separately compiled modules?

2019-09-07 Thread Jacob Carlborg via Digitalmars-d-learn

On 2019-09-06 21:03, Max Samukha wrote:

Is there any practical use of having identically named .d and .di 
alongside?


Same as in C/C++. This allows you to have a header file if you want to 
distribute a closed source library.


--
/Jacob Carlborg


  1   2   3   4   5   6   7   >