Re: D doesn't have weak references. So how can I make a associative array of objects without preventing their destruction?

2024-05-09 Thread evilrat via Digitalmars-d-learn

On Thursday, 9 May 2024 at 00:39:49 UTC, Liam McGillivray wrote:


What's a good way I can achieve what I'm trying to do, using 
either reference counting or a garbage-collected object?


There is libraries like `automem`[1] that implements refcounting 
and more.
Without showing your code for ref counted struct we can't help 
you.


As for weak references, maybe you could "trick" the GC by using 
the fact that simple types are not scanned, i.e. do something 
like this but I have no idea if this is going to work at all, 
alternatively you can also try using `ubyte[size_t.sizeof]`.


Keep in mind that classes is already references so you don't need 
that extra pointer for classes, can be versioned with template 
specialization.


```d
struct WeakRef(T) {
private size_t _handle; // same size as a pointer

this(T* ptr) {
_handle = cast(size_t) ptr;
}

T* getRef() {
return cast(T*) _handle;
}

// do the rest ...
}
```

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


Re: D doesn't have weak references. So how can I make a associative array of objects without preventing their destruction?

2024-05-10 Thread evilrat via Digitalmars-d-learn

On Friday, 10 May 2024 at 13:27:40 UTC, Dukc wrote:

Steven Schveighoffer kirjoitti 10.5.2024 klo 16.01:

On Friday, 10 May 2024 at 11:05:28 UTC, Dukc wrote:
This also gets inferred as `pure` - meaning that if you use 
it twice for the same `WeakRef`, the compiler may reuse the 
result of the first dereference for the second call, without 
checking whether the referred value has changed!


This would be weak pure since the reference is mutable. This 
cannot be memoized.


The difference is the type. With a pointer parameter (both a 
bare one and one in a struct), the compiler can cache the 
result only when the pointed data is similar. However, here we 
have an integer parameter. It can be cached if it itself is 
similar to the one in the other function call. The compiler 
doesn't have to know, nor can know, when a `size_t` is a 
pointer in disguise.


This why I would just use ref counting if I were the topic 
author, trying to be smart will often comes back when one doesn't 
expect.


And as stated by previous author if the goal is to have 
self-clearable weak reference it will need some infrastructure 
anyway, so tbh this will greatly outweight any possible benefits 
of having weak refs.


Re: need help to use C++ callback from garnet

2024-05-29 Thread evilrat via Digitalmars-d-learn

On Wednesday, 29 May 2024 at 07:47:01 UTC, Dakota wrote:
I try use 
https://github.com/microsoft/garnet/blob/main/libs/storage/Tsavorite/cc/src/device/native_device_wrapper.cc from D



Not sure how to make this work with D:

```c++
	EXPORTED_SYMBOL FASTER::core::Status 
NativeDevice_ReadAsync(NativeDevice* device, uint64_t source, 
void* dest, uint32_t length, FASTER::core::AsyncIOCallback 
callback, void* context) {
		return device->ReadAsync(source, dest, length, callback, 
context);

}

	EXPORTED_SYMBOL FASTER::core::Status 
NativeDevice_WriteAsync(NativeDevice* device, const void* 
source, uint64_t dest, uint32_t length, 
FASTER::core::AsyncIOCallback callback, void* context) {
		return device->WriteAsync(source, dest, length, callback, 
context);

}
```

I need to define `FASTER::core::AsyncIOCallback callback` from 
D, any way to workaround ? (like modify garnet source code to 
support pass a C function callback)


I am newbie to C++ and D, any help will be appreciate



(here is the signature of callback)
https://github.com/microsoft/garnet/blob/ade2991f3737b9b5e3151d0dd0b614adfd4bcecd/libs/storage/Tsavorite/cc/src/device/async.h#L25

```cpp
typedef void(*AsyncIOCallback)(IAsyncContext* context, Status 
result, size_t bytes_transferred);

```

This can be written as following to match namespace and mangling 
scheme, assuming IAsyncContext is opaque pointer here, though I 
don't remember if enum need namespace as well.

But no guarantess anyways, try it and adapt it.
Also I can't remember if string list makes proper namespace or 
you should put `FASTER.core` instead (without quotes).


```d
enum Status : ubyte {
  Ok = 0,
  Pending = 1,
  NotFound = 2,
  OutOfMemory = 3,
  IOError = 4,
  Corruption = 5,
  Aborted = 6,
}

extern(C++, "FASTER", "core")
class IAsyncContext;

alias AsyncIOCallback = extern(C++, "FASTER", "core") void 
function(IAsyncContext context, Status result, size_t 
bytes_transferred);

```


Re: How to pass in reference a fixed array in parameter

2024-06-04 Thread evilrat via Digitalmars-d-learn

On Tuesday, 4 June 2024 at 12:22:23 UTC, Eric P626 wrote:
I am currently trying to learn how to program in D. I thought 
that I could start by trying some maze generation algorithms. I 
have a maze stored as 2D array of structure defined as follow 
which keep tracks of wall positions:


~~~
struct s_cell
{
   bool north = true;
   bool east = true;
   bool south = true;
   bool west = true;
}
~~~

I try to create a 2D array of fixed length and pass it in 
parameter as a reference. Normally, in C, I would have used a 
pointer as parameter, and pass the address of the array. Here, 
I thought it would have been easier just to pass a slice of the 
array, since a slice is a reference to the original array. So I 
wrote the signature like this:


~~~
void main()
{  writeln("Maze generation demo");

   s_cell [5][5] maze;
   print_maze (maze);

}

void print_maze ( s_cell [][] maze )
{
}
~~~

My idea is that print_maze use a slice of what ever is sent in 
parameter. Unfortunately, I get the following error message:


~~~
Error: function `mprmaze.print_maze(s_cell[][] maze)` is not 
callable using argument types `(s_cell[5][5])`
  cannot pass argument `maze` of type `s_cell[5][5]` to 
parameter `s_cell[][] maze`

~~~

I tried to find a solution on the internet, but could not find 
anything, I stumble a lot on threads about Go or Rust language 
even if I specify "d language" in my search.


You have declared static array here, they cannot be implicitly 
converted to dynamic arrays.


It is not very obvious but it is a part of language design to 
avoid unnecessary GC allocations and for C compatibility reasons 
in some cases (e.g. strings known at compile implicitly has null 
appended to it to be able to pass pointer as is to C functions).


IIRC you can explicitly cast it to s_cell[][] to make it work but 
it will allocate new array when you append to it.


Else is there other ways to pass an array as reference using 
parameter modifiers like: ref,in,out ...


`ref` is exactly for that.


Else, can it be done the C way using pointers?


absolutely, even ref behind the scenes will basically do the same 
thing anyway.






Re: How to pass in reference a fixed array in parameter

2024-06-05 Thread evilrat via Digitalmars-d-learn

On Wednesday, 5 June 2024 at 06:22:34 UTC, Eric P626 wrote:

On Tuesday, 4 June 2024 at 16:19:39 UTC, Andy Valencia wrote:

On Tuesday, 4 June 2024 at 12:22:23 UTC, Eric P626 wrote:


Thanks for the comments. So far, I only managed to make it work 
by creating a dynamic array and keeping the same signature:


~~~
void main()
{  s_cell [][] maze = new s_cell[][](5,5);
   print_maze (maze);
}

void print_maze ( s_cell [][] maze )
{
}
~~~

Now according to the book, it's possible to assign a slice from 
a fixed array. This code will compile:


~~~
int[12] monthDays = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 
30, 31 ];

int[] a_slice = monthDays;
~~~


for simple cases like this it might work, but 2d array is not 
even contiguous, simpler case like s_cell[5][] might work too.


How come the assignment does not work when passing a parameter. 
I tried the following and it failed:


~~~
s_cell [5][5] maze;
s_cell [][] sliced_maze = maze;
~~~

with this message:

~~~
Error: cannot implicitly convert expression `maze` of type 
`s_cell[5][5]` to `s_cell[][]`

~~~

Is it because it's a 2D array (slice of slice)? I need to 
manually copy each slice manually, or use a utility function to 
do the copy? This is why it cannot auto-magically do it with 
just when passing a parameter.




very likely this is the only solution - make a dynamic array by 
copying all elements.
there was few old bug tracker issues discussed wrt to static 
arrays and join function but there is seems to be no agreement so 
far.




~~~
Error: function `mprmaze.create_maze(s_cell[][]* maze)` is not 
callable using argument types `(s_cell[5][5]*)`
cannot pass argument `& maze` of type `s_cell[5][5]*` to 
parameter `s_cell[][]* maze`

~~~

Now I think it expect a 2D array of pointers instead of a 
pointer on a 2D array.


It's also not clear if there is a difference between those 2 
notations:


~~~
&maze
maze.ptr
~~~



there is, array itself is a tuple of length and pointer, the .ptr 
notation is just the data location, this is what you usually pass 
to C functions and not &maze itself.


to sum up, i wasn't able to make fixed-size arrays to work with 
dynamic arrays without making a copy, and I don't think this will 
change in the future because of various reasons including type 
system limitations and binary object formats.


so if you really absolutely need static arrays for example to 
avoid GC allocations in hot path than you need to make function 
that takes fixed size array.


in addition to that spec 
(https://dlang.org/spec/arrays.html#static-arrays) says static 
arrays is passed by value, unlike dynamic arrays that even when 
passed as length-and-pointer tuple will allow writing back to 
original data.





Re: How to pass in reference a fixed array in parameter

2024-06-05 Thread evilrat via Digitalmars-d-learn

On Wednesday, 5 June 2024 at 11:27:32 UTC, Nick Treleaven wrote:

On Wednesday, 5 June 2024 at 09:24:23 UTC, evilrat wrote:
for simple cases like this it might work, but 2d array is not 
even contiguous,


A 2D static array is contiguous:
https://dlang.org/spec/arrays.html#rectangular-arrays

D static arrays, while using the same syntax, are implemented 
as a fixed rectangular layout in a contiguous block of memory


Yeah ok, i might have messed up with columns last time, but it 
works.


```d
int[5][5] test;

foreach(i; 0..5) {
foreach(j; 0..5) {
test[i][j] = i * 5 + j;
}
}

foreach(i; 0..25) {
assert(test[0].ptr[i] == i);
}
```


Re: Unintentional sharing?

2024-06-06 Thread evilrat via Digitalmars-d-learn

On Thursday, 6 June 2024 at 17:49:39 UTC, Andy Valencia wrote:
I was using instance initialization which allocated a new 
object.  My intention was this initialization would happen 
per-instance, but all instances appear to share the same 
sub-object?  That is, f1.b and f2.b appear to point to a single 
object?  Obviously I moved the new into the initializer code, 
but I hadn't appreciated how initial instance values were 
calculated once.  Interestingly, this makes it similar to how 
Python calculates default argument values for functions.


class Bar {
int z = 3;
}

class Foo {
auto b = new Bar();
}

void
main() {
import std.stdio : writeln;

auto f1 = new Foo(), f2 = new Foo();
f1.b.z = 0;
writeln(f2.b.z);
}


What you are seeing here is indeed sharing reference.
It happens because type initializer sets fields after memory 
allocation but before constructor call, and so since it is using 
value known at compile time all instances will have share same 
reference.


https://dlang.org/spec/class.html#constructors


Re: How to use D without the GC ?

2024-06-12 Thread evilrat via Digitalmars-d-learn
On Wednesday, 12 June 2024 at 17:00:14 UTC, Vinod K Chandran 
wrote:

On Wednesday, 12 June 2024 at 10:16:26 UTC, Sergey wrote:


Btw are you going to use PyD or doing everything manually from 
scratch?


Does PyD active now ? I didn't tested it. My approach is using 
"ctypes" library with my dll. Ctypes is the fastes FFI in my 
experience. I tested Cython, Pybind11 and CFFI. But None can 
beat the speed of ctypes. Currently the fastest experiments 
were the dlls created in Odin & C3. Both are non-GC languages.


It is probably not that well maintained, but it definitely works 
with python 3.10 and maybe even 3.11, i use it to interface with 
pytorch and numpy and PIL, but my use case is pretty simple, i 
just write some wrapper python functions to run inference and 
pass images back and forth using embedded py_stmts. the only 
problem is that it seems to leak a lot PydObjects so i have to 
manually free them, even scope doesn't helps with that which is 
sad.


example classifier python
```python
def inference(image: Image):
""" Predicts the image class and returns confidences for 
every class

To get the class one can use the following code
> conf = inference(image)
> index = conf.argmax()
> cls = classes[index]
"""

# this detector doesn't works with more than 3 channels
ch = len(image.getbands())
has_transparency = image.info.get('transparency', None) is 
not None

if ch > 3 or has_transparency:
image = image.convert("RGB")

image_tensor = prep_transform(image).float()
image_tensor = image_tensor.unsqueeze_(0)

# it is fast enough to run on CPU
#if torch.cuda.is_available():
#image_tensor.cuda()

with torch.inference_mode():
# NOTE: read the comment on model
output = model(image_tensor)
index = output.data.numpy()

return index
```

and some of D functions

```d
ImageData aiGoesB(string path, int strength = 50) {
try {
if (!pymod)
py_stmts("import sys; 
sys.path.append('modules/xyz')");

initOnce!pymod(py_import("xyz.inference"));
if (!pymod.hasattr("model"))
pymod.model = pymod.method("load_model", 
"modules/xyz/pre_trained/weights.pth");


PydObject ipath = py(path);
scope(exit) destroy(ipath);

auto context = new InterpContext();
context.path = ipath;

context.py_stmts("
from PIL import Image
image = Image.open(path)
ch = len(image.getbands())
if ch > 3:
image = image.convert('RGB')
");

// signature: def run(model, imagepath, alpha=45) -> 
numpy.Array
PydObject output = pymod.method("run", pymod.model, 
context.image, 100-strength);

context.output = output;
scope(exit) destroy(output);

PydObject shape = output.getattr("shape");
scope(exit) destroy(shape);

// int n = ...;
int c = shape[2].to_d!int;
int w = shape[1].to_d!int;
int h = shape[0].to_d!int;

// numpy array
void* raw_ptr = output.buffer_view().item_ptr([0,0,0]);

ubyte* d_ptr = cast(ubyte*) raw_ptr;
ubyte[] d_img = d_ptr[0..h*w*c];

return ImageData(d_img.dup, h ,w ,c);
} catch (PythonException e) {
// oh no...
auto context = new InterpContext();
context.trace = new PydObject(e.traceback);
context.py_stmts("from traceback import format_tb; trace 
= format_tb(trace)");

printerr(e.py_message, "\n", context.trace.to_d!string);
}
return ImageData.init;
```



Re: Pointer to dlang spec for this alias construct?

2024-06-16 Thread evilrat via Digitalmars-d-learn

On Monday, 17 June 2024 at 04:32:50 UTC, Andy Valencia wrote:

In the alias:

alias Unshared(T) = T;
alias Unshared(T: shared U, U) = U;

as used in:

cast(Unshared!mytype)value

turns a mytype with shared attribute into one without shared.

I deduce the alias is using some sort of type matching and 
decomposition?


I've read through the language spec, and didn't spot this 
mechanism.  Can somebody tell me what section of the spec 
covers this very interesting mechanism?


Thanks in advance,
Andy


not sure if it works the same with template arguments but here is 
the rules

https://dlang.org/spec/expression.html#IsExpression


Re: Being reading a lot about betterC, but still have some questions

2024-07-09 Thread evilrat via Digitalmars-d-learn

On Tuesday, 9 July 2024 at 07:54:12 UTC, kiboshimo wrote:

Hi,

Some stuff must look obvious to an experienced programmer so 
they are not explicit on articles and documentation over the 
internet. I'm somewhat inexperienced, so:


- betterC does not need glue code to interop with C. Does it 
achieve this by "gluing" behind the scenes? I've read in a 
comment somewhere that the ABI is the same, but idk people say 
lots of things.


- betterC cannot be used with some parts of phobos. Should I 
worry I won't be able to use essential stuff for systems 
programming? Things like atomics.
// If that is the case, can I supplant these low-level stuff 
with an equivalent C library? (I don't think so, but I'm 
hopefull).


- betterC can be compiled to WASM, but some of phobos can't, so 
basically same worries as above. I'm afraid to lose some 
essential systems stuff that I could not replace.


I'm going to try a project with raylib and WASM. Really liked 
the idea of doing it with betterC to start my systems 
programming journey (tough start, don't care, just fill me in 
if you want to).


Thanks :)


betterC is just a reduced D subset that was intended to help 
porting C code over to D to an unsupported platforms where the 
full D runtime (provides GC and other advanced language features) 
is not yet implemented or not feasible (like microcontrollers, 
although D is not very friendly to 8-bit hardware).


Because it turns off many advanced features it means there is no 
GC and runtime type information(RTTI), many of the phobos 
functions relies on these features.


All this makes it very advanced feature not intended for mass 
users.


- Don't confuse it with extern(C) linkage too, extern(C) is what 
makes it compatible with C ABI.

- Don't confuse it with an importC feature.

- It is not betterC to blame for lacking standard library support 
but because phobos is not implemented for it, of course you can 
do it yourself if you really wanted to but certain D concepts 
(like ranges) will be much harder to do without GC support.


- You can't have regular D classes (extern(D)) in betterC as they 
rely on RTTI, however you can have extern(C++) classes.


- If your C/C++ library provides atomics, you can do this, but 
probably you can use some of the phobos as this is pretty low 
level stuff.


---

What it is:
- reduced language subset to allow "easier" targeting to very 
modest hardware or other unsupported systems
- it makes the compiler emits errors if you accidentally use some 
of full D features


What it is NOT:
- it is not a C compiler
- it won't accept your C files as if it is D
- it won't just magically port C code for you




Re: How do you typically debug / write D code (Visual Studio - known to be broken in Error pane etc), VScode - I get this error...

2024-08-19 Thread evilrat via Digitalmars-d-learn
On Monday, 19 August 2024 at 10:59:33 UTC, Daniel Donnelly, Jr. 
wrote:
I give up on Visual Studio VisualD plugin as it's had the same 
issues for over five years, and currently my program runs from 
the command line, but VisualD complains with a 528 nonsensical 
errors.


So I investigated using VScode instead (I do need a debugger), 
and I get this:


```
Couldn't find a debug adapter descriptor for debug type 
'code-d' (extension might have failed to activate)

```

I have the D-support plugin installed and it auto-creates a 
Launch config when I select it from the dropdown after clicking 
Add Configuration.


The launch.json config looks like this:

```
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: 
https://go.microsoft.com/fwlink/?linkid=830387

"version": "0.2.0",
"configurations": [
{
"type": "code-d",
"request": "launch",
"dubBuild": true,
"name": "Build & Debug DUB project",
"cwd": "${command:dubWorkingDirectory}",
"program": "${command:dubTarget}"
}

]
}

```

I've tried both DUB vs non-DUB launch config.  Same error 
either way.


So how do you guys efficiently debug D if there exists no 
working environment or is there a nice IDE I'm unaware of?


In windows you need "C++" extension from Microsoft as it has 
native debugger for that OS.


Re: Associative Array, get value instead of poiter using `if (auto ..)`, possible?

2024-09-01 Thread evilrat via Digitalmars-d-learn

On Sunday, 1 September 2024 at 08:50:53 UTC, ryuukk_ wrote:


if checking for/getting a value from a hashmap requires all 
that crap, then perhaps something is wrong with the language, 
and it perhaps isn't the one i should have picked for the task


my mistake perhaps, not yours


besides, i do use the language features in my project, 
templates and mixins to solve larger problems, it's great, and 
reason why i picked D





An alternative would be yet another template wrapper for get 
value that takes a dictionary an a lambda and call that lambda 
only if value is present, this means you no longer do the if, but 
rather a "cryptic" call like in some other languages.


pseudo code:
```d
// helper function
void withKey(V,K,L)(V[K] dict, K key, lazy L dostuff) {
if (auto value = dict.get(K)) {
doStuff(*value);
}
}

// usage

string[int] counters;
counters["foo"] = 42;
counters.withKey("foo", (value) {
assert(value == 42);
});
```


Re: What happened to Circular Studio?

2022-06-08 Thread evilrat via Digitalmars-d-learn
On Monday, 6 June 2022 at 21:07:58 UTC, Steven Schveighoffer 
wrote:

On 6/6/22 3:46 PM, Jack wrote:
I just found out a game using D to develop games but later I 
see the last updates on the github, web site, twitter etc is 
from 2015. Does anyone knows what happend to the company?


It appears to be just a playground for a bunch of friends at 
RIT, I'm not sure how much of a "company" this was.


But, there is activity in the github issues list, circa 
November 2020: 
https://github.com/Circular-Studios/Dash/issues/249


But who knows, probably just fizzled out. I admit, I never 
heard of them.


-Steve


Their engine was unfortunate enough to land before the great 
language update in 2015-2016, basically updating it to work with 
current D well be such a PITA that it is easier to rewrite from 
scratch, I did tried to update it but eventually abandoned it 
because there is tons of dependencies from that era that was 
abandoned as well.


It has some nice ideas like Unity-like class registration and 
metadata using CTFE but that's basically it...
They even have minor issues in shaders like right-handed math 
mixed with left-handed math resulting in broken shadows and more 
issues.


Re: Background thread, async and GUI (dlangui)

2022-07-11 Thread evilrat via Digitalmars-d-learn

On Sunday, 10 July 2022 at 09:15:59 UTC, Bagomot wrote:
Based on Thread, I managed to do what I intended. I have not 
yet been able to figure out how to do the same through the Task.


Here in the example, when you click on the Start button, a 
worker is launched that updates the progress bar.


...

Do you have any suggestions how to do it more beautifully and 
not through the Thread? In particular, I would like to see the 
comments of the dlangui developers (@GrimMaple).


Since you've already used `executeInUiThread` you can now just 
move your Thread.run() implementation to a free function and run 
it using task instead.
`executeInUiThread` will ensure that passed delegate will be 
called in UI thread making it safe to call from another thread or 
task.


Not sure about default widgets, but in some cases for your custom 
properties you might need to `invalidate()` widget to trigger 
redraw.


Anyway you will need a reference to your widget to update 
progress bar value, options are:
- It can be done in place where you start your task (e.g. inside 
button click event, delegates can access call site scope)
- get widget reference directly by using 
`getWidgetById("WIDGET_ID")` (or how it was called, though you 
will need to assign ID to your progress bar and remember it)
- use signal-slot mechanism (you still need widget reference to 
bind events)



btw, have you tried googling this forum? I think there was exact 
same question with curl & dlangui a year or two ago, maybe it has 
an answer or at least tips you need?


Anyway for curl notify progress delegate you can just do it 
inside that delegate using `executeInUiThread` there.


like in example here 
https://dlang.org/library/std/net/curl/curl.on_progress.html

adjusting to somewhat above will now look like (not tested)

```d
// download button click event
void downloadbutton_Click()
{
  auto progressBar = (get progress bar reference);

  Curl curl;
  curl.initialize();
  curl.set(CurlOption.url, "http://dlang.org";);
  curl.onProgress = delegate int(size_t dltotal, size_t dlnow, 
size_t ultotal, size_t ulnow)

  {
// even though onProgress can be run in another thread this 
delegate will be run on next UI tick
executeInUiThread( (){ progressBar.setProgress(dlnow/dltotal 
* 100); } );

return 0;
  };
  curl.perform();
}
```


Re: Vibe.d serve files from filesystem

2023-01-12 Thread evilrat via Digitalmars-d-learn

On Wednesday, 11 January 2023 at 18:56:47 UTC, eXodiquas wrote:

Hello everyone,

I build a web tool that allows people to upload some files. 
Those files should not be public, so I copy them into a folder 
hidden away on the filesystem. But, I want an authenticated 
user to be able to look at them. Those files are PDFs and 
mp3/4s. So my idea was to use an `iframe` with a 
`src="path/to/file"` but this is not working, because vibed 
wants to map it to a route but there is and there should be 
none. Is there a way to use iframes in this way, or do I need 
to approach this problem differently?


Thanks in advance.

eXo


You will probably need to write a custom route handler that 
handles some authentication and returns files in response to a 
user.


Since vibe.d routes handled in order you will need to add such 
route before generic '*' route.


Take a look at this example
https://vibed.org/docs#http-routing

You can probably just write a handler like addUser for 
router.get('*', serveMyFiles) and write your own file handling 
logic.



```d
// PSEUDOCODE

// use this handler in router.get('*', serveMyFiles)
void serveMyFiles(HTTPServerRequest req, HTTPServerResponse res)
{
  enforceHTTP("file" in req.form, HTTPStatus.badRequest, "No file 
specified.");
  // don't just use raw input from the user, users can access 
your whole filesystem with some hackery!!

  res.writeBody(readfile("/users/"~req.form["file"]));
}

```



Re: Non-ugly ways to implement a 'static' class or namespace?

2023-01-20 Thread evilrat via Digitalmars-d-learn
On Friday, 20 January 2023 at 13:17:05 UTC, Ruby The Roobster 
wrote:
On Friday, 20 January 2023 at 13:03:18 UTC, thebluepandabear 
wrote:

ll
a function without instantiating said class, as functions act 
on the class object.


Ok, thanks.

I think D should implement something similar to `static class` 
but I doubt it will happen.


D isn't Java, and never will be.  If you want similar 
functionality, you put the functions in a separate file, and 
add the line to the top of it:


```d
module modulename;
```

and title the file modulename.d.  Then you can use this module 
as a .class file in java by adding


```d
import modulename;
```

to the file that uses it.


Also there is various import options such as renamed import or 
static import(doesn't add module to a scope thus requiring to 
fully qualify it)


static import, can be used to somewhat mimic namespaces, more 
complex scenario would be making a module consisting of public 
imports to group things together, but I don't think it is common 
in D.

https://dlang.org/spec/module.html#static_imports

```d
static import std.stdio;

void main()
{
  // nope, this function will not be resolved, compilation error
  // wrtiteln("hello");

  // ok
  std.stdio.writeln("hello");
}
```


Re: Function which returns a sorted array without duplicates

2023-01-21 Thread evilrat via Digitalmars-d-learn

On Sunday, 22 January 2023 at 04:42:09 UTC, dan wrote:
I would like to write a function which takes an array as input, 
and returns a sorted array without duplicates.



```d
private S[] _sort_array( S )( S[] x ) {
  import std.algorithm;
  auto y = x.dup;
  y.sort;
  auto z = y.uniq;
  // Cannot just return z; this gives:
  // Error: cannot implicitly convert expression `z` of type
  // `UniqResult!(binaryFun, uint[])` to `uint[]`


uniq and other algorithms often returns a lazy range, you can 
build an array by using `std.array.array()`


https://dlang.org/phobos/std_array.html#array

try something like this or just `return array(y.uniq);`

```d
private S[] _sort_array( S )( S[] x ) {
import std.algorithm;
import std.array;
return x.dup
   .sort
   .uniq
   .array();
}
```

And IIRC you probably don't need `dup` as sort produces a lazy 
range.






Re: Hipreme's #8 Tip of the day - Using custom runtime with dub projects

2023-01-22 Thread evilrat via Digitalmars-d-learn

On Sunday, 22 January 2023 at 16:57:56 UTC, Hipreme wrote:


The way to use dub's packages is by using the DFLAGS. With 
DFLAGS, I can set the import path to my own DRuntime and own 
std. That way I can make the dependencies behave more or less 
the same, this is an example of what is being done now:


Keep in mind that you'll probably need to setup some env 
variables such as mine done for making your script a little 
more portable to other developer's PCs. I would really like if 
there was a way to define global dflags on dub though.


Can't you just use env variable[1] and put into dub dflags like 
this?


https://github.com/Superbelko/ohmygentool/blob/cc75d915a8df8bdc2bba628df305d421151994a1/dub.json#L11


_(note that some of the listed predefines doesn't work in some 
sections though, a bug maybe?)_

[1] https://dub.pm/package-format-json.html#environment-variables


Re: Hipreme's #8 Tip of the day - Using custom runtime with dub projects

2023-01-22 Thread evilrat via Digitalmars-d-learn

On Sunday, 22 January 2023 at 18:16:35 UTC, Hipreme wrote:


Nope. Those DFLAGS environment variable is used to affect 
projects such as my dependencies. For example, my dependency 
needs to be built using my own runtime. The dflags defined in 
the dub.json only affect the current project, not its 
dependencies


Ah ok, got it, the compiler will fetch them for a whole session 
no matter what is currently being built.


Though this approach will make it harder to anyone who might want 
to use your project/library if this requirement remains for a 
user's project.


Re: How to a link to a C library to create static bindings?

2023-01-27 Thread evilrat via Digitalmars-d-learn
On Saturday, 28 January 2023 at 02:40:58 UTC, thebluepandabear 
wrote:


I am really confused as to how I even am supposed to get the 
library name in the first place, which is another thing that is 
confusing me.




It is up to the library author to choose a name. The extensions 
is `.so/.dll/.dylib` for shared libraries on nix/Windows/Mac and 
`.a/.lib/???` for static libraries.


The second part, this looks like sfml graphics depends on sfml 
render or window or something like that, you'd better check 
`readelf -d sfml-render.so | grep 'NEEDED'` if you have dynamic 
libs to get a clue what it might need, or go search library that 
contains missing symbols by hand.




Re: Using Windbg to debug D applications and unittests

2023-02-25 Thread evilrat via Digitalmars-d-learn
On Saturday, 25 February 2023 at 15:55:33 UTC, solidstate1991 
wrote:
I had a lot of trouble trying to get Visual Studio to catch 
handled exceptions


VisualD for Visual Studio provides some extra help with 
displaying your data in debugger and on Windows is the best you 
can get for D.


You can use Visual Studio Code + code-d to debug, but it is not 
as good as full Visual Studio counterpart.


Anyway you can use LDC with -gc flag to improve this situation a 
bit as it will mimic C++ debug info that is more compatible with 
said debuggers than D one.


Re: Using Windbg to debug D applications and unittests

2023-02-25 Thread evilrat via Digitalmars-d-learn
On Saturday, 25 February 2023 at 16:58:44 UTC, solidstate1991 
wrote:


I used to use Visual Studio, but I forgot how to set it up 
properly to break on handled throws. Now it doesn't do anything 
if throws are handled in any fashion, and I can't find an 
option to change it (it was removed maybe?).


Turn on exception settings panel in top menu bar:
  Debug->Windows->Exceptions Settings (Crtl+Alt+E)

My settings for D is full "D exceptions", under Win32 check "D 
Exception", or just click "Restore to default settings" in there 
on top of that panel.





Re: Using Windbg to debug D applications and unittests

2023-02-25 Thread evilrat via Digitalmars-d-learn
On Saturday, 25 February 2023 at 19:31:10 UTC, solidstate1991 
wrote:


Well, VS turned to be even less cooperative than before. Now it 
only loads and runs a specific old version of an EXE file.


I'm asking around for other debuggers, I'm definitely moving to 
another.


Nothing happens without a reason, check your project settings and 
make sure that for debugging you have correct paths, command, and 
arguments.


Even with no debug info and no project you can just drop an 
executable to an empty VS window and start debugging it, at the 
very least it can show disassembly.
If there is .pdb files with debug info next to your executable 
you can just drag and drop your D source files and then add 
breakpoints in that source files and it will work.


Re: I don't understand betterC

2023-09-01 Thread evilrat via Digitalmars-d-learn

On Friday, 1 September 2023 at 13:17:08 UTC, confused wrote:
On Friday, 1 September 2023 at 08:19:55 UTC, Richard (Rikki) 
Andrew Cattermole wrote:
``size_t`` is defined in ``object.d`` which is implicitly 
imported into all modules.


If it cannot be found, one of three things is happening:

1) You have messed with some cli args related to picking 
druntime/phobos

2) You have defined a module called object.
3) You have a broken compiler install.


I have in fact defined a module called ``` object ```. How is 
that related to this error?




It is shadowing default implicit "import object;", here a 
demonstration


```d
// this example shows default implicit import of "object" module
// compile this example:
//   ldc2 -c test.d
// output:
//   tuple("object", "core", "main", "thisModule")

// just a random import
import core.stdc.stdio;

void main() { }

alias thisModule = __traits(parent, main);
pragma(msg,  __traits(allMembers, thisModule)); // has implicitly 
imported 'object' module

```



Re: I don't understand betterC

2023-09-01 Thread evilrat via Digitalmars-d-learn

On Saturday, 2 September 2023 at 03:27:51 UTC, confused wrote:
So I guess my next question is why, exactly, classes *can*, in 
fact, be implemented in ``` betterC ```, but are not?


IIRC you can have extern(C++) classes in betterC, the real issue 
is the plain extern(D) classes which has some assumptions that 
are not present in betterC runtime.
Be careful though as extern(C++) classes have a bit different 
behavior where you might not expect it.
Specifically they have different vtable layout and some quirks 
with regard to multiple inheritance which is not available in D.
They might have some different destructor logic, and maybe there 
is more...


Otherwise you will have to mimic "classes" behavior with some 
template magic, just like OOP in C similar to COM model or gtk 
gobject, this means no fancy keyword and no language support for 
them though. But with all the templates and CTFE this shouldn't 
be a problem.


Also if you have read this forums regarding betterC... well, I 
think its only valid real use cases are tiny microcontrollers and 
WebAsm (because of GC), but the latter case can probably avoided 
with custom D runtime and people in fact has crafted some custom 
implementations.


Re: I don't understand betterC

2023-09-04 Thread evilrat via Digitalmars-d-learn

On Monday, 4 September 2023 at 07:39:21 UTC, confused wrote:


So then I guess I'd still like to know how I'm expected to 
store and access an array of characters without the C runtime 
as I tried in my original post.


Without C runtime functions such as malloc you can still have 
fixed-length arrays, for string variables the compiler will emit 
null-terminated string at compile time in cases like that making 
it compatible with C functions.


Note that it not the case for other string operations like concat 
operator (is it available in betterC?), in that case if you want 
to pass the resulting string you have to add null terminator by 
hand.


If you need to allocate memory at runtime and still wan't to 
avoid C runtime, well I guess you have to do some syscalls then...
Or use another allocator library, jmalloc maybe? Though I don't 
have the experience with them and don't know if they are using C 
runtime somewhere inside or handle that low level OS/syscalls 
stuff by itself.


Re: malloc error when trying to assign the returned pointer to a struct field

2023-09-08 Thread evilrat via Digitalmars-d-learn

On Friday, 8 September 2023 at 07:59:37 UTC, rempas wrote:

I do have the following struct:

```d
struct Vec(T) {
private:
  T* _ptr = null; // The pointer to the data
  u64 _cap = 0;   // Total amount of elements (not bytes) we 
can store


public:
  /* Create a vector by just allocating memory for it. The null 
terminator is not set for
 strings as, the vector is considered empty and we should  
first push something to it

 in order to use it! */
  this(i64 size) {
this._len = 0;
this._cap = size;

static if (is(T == char)) { size += 1; } // Additional 
space for the null terminator

this._ptr = cast(T*)malloc(size);
  }
}
```

That's some minimal code that I do have just to showcase it. 
So, some times, this work will works, some others, it will give 
me the following error:


`Fatal glibc error: malloc.c:2594 (sysmalloc): assertion 
failed: (old_top == initial_top (av) && old_size == 0) || 
((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) 
&& ((unsigned long) old_end & (pagesize - 1)) == 0)`


The problem seems to happen when the pointer that is returned 
from `malloc` is assigned to the `_ptr` field. If I just assign 
it to a variable and don't assign anything to `_ptr`, it will 
work!


Is there any possible that there is a compiler bug? I do use 
ldc2 and `betterC`!


Hard to tell from that code but it is quite unlikely there is a 
compiler bug in such simple use case.


I assume you already tried debugging your program, right?

So how about to diagnose a bit more, what if you enforce check 
before malloc that size>0, and second - from that example it is 
unclear how you are using that struct, so maybe add else 
statement static assert to see if it is misused somewhere else in 
your codebase?


Also this example doesn't have len field, depending on how you 
use with regard to cap this could be a source of problems too.


Re: malloc error when trying to assign the returned pointer to a struct field

2023-09-08 Thread evilrat via Digitalmars-d-learn

On Friday, 8 September 2023 at 11:50:52 UTC, rempas wrote:


That's interesting, I wasn't able to find something else! The 
bug happens when I run the testing suit and well... the tests 
before pass so I cannot find anything that goes wrong except 
for the fact that I do not free the memory that is allocated 
(on purpose).




You run with -unittest compiler flag? Well, that does nothing for 
me with betterc (without it is ok).


I did stupid and unsafe things like malloc(0) and writing out of 
bounds but still no crash, it works fine.


I guess it depends on your libc, tested this on ubuntu 23.04 with 
gcc12 install and ldc 1.32.2


```d
import core.stdc.stdlib;
import core.stdc.stdio;

alias u64 = ulong;
alias i64 = long;

struct Vec(T) {
private:
  T* _ptr = null; // The pointer to the data
  u64 _cap = 0;   // Total amount of elements (not bytes) we can 
store

  u64 _len = 0;

public:
  /* Create a vector by just allocating memory for it. The null 
terminator is not set for
 strings as, the vector is considered empty and we should  
first push something to it

 in order to use it! */
  this(i64 size) {
this._len = 0;
this._cap = size;

static if (is(T == char)) { size += 1; } // Additional space 
for the null terminator

this._ptr = cast(T*)malloc(size);
  }

  ref T opIndex(size_t idx) { return _ptr[idx]; }
}

extern(C)
void main()
//unittest
{
enum el = 3;
auto vec = Vec!char(10);
assert(vec._ptr);
vec[el] = 'h';
assert(vec[el] == 'h');
printf("ptr = %p\n", vec._ptr);
printf("vec ptr = %p\n", &vec[el]);
printf("vec local = %p\n", &vec);
printf("vec[%d] = %c\n", el, vec[el]);
foreach (i; 0..vec._cap) {
  printf("-");
}
printf("\n");
foreach (i; 0..vec._cap) {
  printf("%d", vec[i]);
}
printf("\n");
printf("run ok\n");
}
```

ldc2 -betterC -run membug.d

output

```
ptr = 0x55cb701de2a0
vec ptr = 0x55cb701de2a3
vec local = 0x7fffa1542258
vec[3] = h
--
00010400
run ok
```


Re: pipeProcess output to hash string

2023-09-09 Thread evilrat via Digitalmars-d-learn

On Saturday, 9 September 2023 at 16:49:30 UTC, user1234 wrote:


not sure why you append "/?" to the program name.


Windows maybe? Try this.

auto result = std.process.pipeProcess(["whoami", "/?"], redirect);






Re: change object class

2023-09-17 Thread evilrat via Digitalmars-d-learn
On Sunday, 17 September 2023 at 15:05:59 UTC, Vitaliy Fadeev 
wrote:
It works! But I want to ask how to make this 100% the best of 
the best?

What should I consider before changing ```__vptr``` ?


If that works for you with that constraint of having exact memory 
layout then it should be ok.


This however is very uncommon pattern and your library users 
might reject it so keep that in mind if you are going to make 
public library.


Other than that I would suggest at least to make that cast method 
to return a shallow copy because messing with "this" ptr can be 
dangerous (make sure to try it with const objects and optimized 
release builds before using this everywhere).


An even better (at least safer, in theory) option would be to 
make "View" or handle struct that wraps an object(pointer) and 
tracks such transformations.


Of course to think of it now there is yet another opportunity - 
why not to look for something like ECS then?
Because you seem to already treat your objects purely as data 
containers, that way you can safely detach data from logic and 
reduce the scope of your components to keep them focused on one 
task.

That is up to you of course.



Re: Meaning of the dot-function syntax

2023-10-01 Thread evilrat via Digitalmars-d-learn

On Sunday, 1 October 2023 at 08:22:48 UTC, dhs wrote:

Hi,

What's the meaning of the dot in the call to writeln() below?

```d
.writeln("Hello there!");
```

I haven't found this in the spec or anywhere else. This is used 
very often in the source code for Phobos.


Thanks,
dhs


It is either means "use global scope writeln" in cases when there 
is local writeln in the scope shadowing global one, or simply a 
chained calls like myarray.filter().sort().map() each on new line.


Re: How to get all modules in a package at CT?

2023-10-05 Thread evilrat via Digitalmars-d-learn

On Thursday, 5 October 2023 at 22:32:36 UTC, mw wrote:


So ModuleInfo contains all the modules (transitive closure) 
built into the current binary that is running?


Is there document about this ModuleInfo?

I only find Struct object.ModuleInfo

https://dlang.org/library/object/module_info.html

Which seems different.


It is opApply() overload on that struct that works with foreach 
or custom delegate.


Since it calls internal stuff there is no point messing up with 
that.


https://github.com/dlang/dmd/blob/d06917a8327027f94b0be0b8e54e47a51ba34134/druntime/src/object.d#L2441


Re: Can't get into debugger in vscode on macOS

2023-10-19 Thread evilrat via Digitalmars-d-learn

On Thursday, 19 October 2023 at 06:03:06 UTC, Daniel Zuncke wrote:
Hello, I need some help getting into the debugger in vscode on 
macOS. It did work some months ago but that was finicky to set 
up. Maybe I am forgetting something now?


I am compiling the project with `dub build --build debug 
--compiler ldc2 --force` (the `-ld_classic` flag to fix the new 
Xcode linker is set in dub.json).


Debugging in the terminal with lldb works as expected `lldb 
bin/dfmt -- --help`.


In vscode I the debug process immediately exits with error (as 
far as I can tell, don't know how to get more output).
All required extensions should be installed since it worked 
some time ago (mainly CodeLLDB, code-d and C++ from what I 
remember).


I have tried 2 launch configs (launch.json):
```json
{
"version": "0.2.0",
"configurations": [
{
"type": "lldb",
"request": "launch",
"name": "debug lldb",
"cwd": "${workspaceFolder}",
"program": "./bin/dfmt",
"args": ["--help"],
},
{
"type": "code-d",
"request": "launch",
"name": "debug code-d",
"cwd": "${workspaceFolder}",
"program": "./bin/dfmt",
"args": ["--help"],
},
]
}
```
And both fail the same way (vscode Debug Console output):
```
Launching: /Users/dz/dev/dfmt/issue578/bin/dfmt --help
Launched process 24999
Process exited with code -1.
```
Any ideas what the problem could be? Can I get more verbose 
output what the problem is after launching the process?


Could it be is that it instantly crashes?

In that case you need to set the breakpoints, it works by default 
in Windows, but not in Linux and probably MacOS too.


You need to set breakpoints for these functions _d_throw, 
_d_throwdwarf (dmd), _d_throw_exception (ldc, i think?).


I'm not exactly sure what is the relevant name for LDC and i'm on 
windows machine so i can't check my debugger config.


With this it will break on throw and you should be able to 
inspect it in debugger.




Re: Symbolic computations in D

2023-10-29 Thread evilrat via Digitalmars-d-learn

On Sunday, 29 October 2023 at 08:55:24 UTC, Dmitry Ponyatov wrote:

Maybe someone played in this topic, and can give some advice:
is D language with its OOP without multiple inheritance and 
maybe other semantic limitations able and good enough to be 
used with these books mechanics?


You can have multiple interfaces, and interfaces can have default 
implementation for its methods.
What really prohibited is to have multiple base classes as this 
will over complicate data layout and the compiler without much 
benefit (if any at all).


What are semantic limitations you talking about? D is much more 
expressive than C++, there is also CTFE and code generation with 
mixins.


Mixins can do pretty much anything preprocessor can, except they 
can't inject self-invocable code, you always need an explicit 
"mixin(foo)" statement, and that's the only limitation compared 
to preprocessor.

IIRC Vibe.d using them for template engine.

Also D has raw strings, just like this
https://github.com/buggins/dlangui/blob/master/examples/dmledit/src/dmledit.d#L73

Which again with mixins can be turned into DSL(domain specific 
language),
with this you can write your own template that parses that string 
and for example builds a widget tree out of it, like this

https://github.com/buggins/dlangui/blob/master/examples/helloworld/src/helloworld.d#L20


Re: Symbolic computations in D

2023-10-29 Thread evilrat via Digitalmars-d-learn

On Sunday, 29 October 2023 at 10:44:03 UTC, ryuukk_ wrote:


If D had tagged union and pattern matching, it would be a great 
candidate to succeed in that field


Well, we sort of have it, just not as good as it can be.

https://dlang.org/phobos/std_sumtype.html

The default example though makes it look like it works only with 
SumType, here is another example from godot-d where match 
compares on types.


``` d
static Variant from(T : GodotType)(T t) {
import std.sumtype : match;

Variant ret;
t.match!(
(Variant.Type t) { ret = cast(int) t; },
(BuiltInClass c) { ret = c.name; },
(Ref!Script s) { ret = s; }
);
return ret;
}
```

Of course there is also third-party libraries that claims to be 
"doing it right".


Re: Translating C precompiler macros to D

2023-11-09 Thread evilrat via Digitalmars-d-learn
On Wednesday, 8 November 2023 at 20:43:21 UTC, solidstate1991 
wrote:
Here's this precompiler macro from Pipewire, on which many 
important inline functions depend on, like this one:


```c
/**
 * Invoke method named \a method in the \a callbacks.
 * The \a method_type defines the type of the method struct.
 * Returns true if the method could be called, false otherwise.
 */
#define spa_callbacks_call(callbacks,type,method,vers,...)  
\
({  
\
const type *_f = (const type *) (callbacks)->funcs;  \
bool _res = SPA_CALLBACK_CHECK(_f,method,vers); 
\
if (SPA_LIKELY(_res))   
\
_f->method((callbacks)->data, ## __VA_ARGS__);  
  \
_res;   
\
})
```

So far, the only way out I see is to turn it into a string 
mixin. (SPA_LIKELY is just a needless precompiler macro for 
labeling things.)


Not sure if it will work in real situations, expect memory errors.
Also I used a fixed type, you should use CTFE to cast data to 
proper function argument types.



```d
import std.stdio;

bool SPA_CALLBACK_CHECK(T)(const (T)* f, string method, uint 
version_)

{
// do some checks...
return true;
}

bool spa_callbacks_call(alias callbacks, alias type, alias 
method, uint vers, Args...)(Args)

{
const (type)* _f = cast(type*) callbacks.funcs;
	bool _res = SPA_CALLBACK_CHECK(_f, __traits(identifier, method), 
vers);

if (_res)
		__traits(getMember, _f, __traits(identifier, method))(cast(int) 
callbacks.data, Args); // callback call

return _res;
}

// your callback, see pipewire docs for real examples
struct Foo
{
void bar(int x) const { import std.stdio; writeln(x);  }
}

// pipewire internals
struct spa_callback
{
const(void)* funcs;
void* data;
}


void main()
{
Foo foo;
	// instead of this naive approach you should use provided 
initialization method
	// but roughly first parameter is pointer to struct of function 
pointers

spa_callback cb = { cast(void*) &foo, cast(void*) 42 };
spa_callbacks_call!(cb, Foo, Foo.bar, 0)();
}
```


Re: What is :-) ?

2023-11-20 Thread evilrat via Digitalmars-d-learn

On Monday, 20 November 2023 at 08:47:34 UTC, Antonio wrote:


Now, I uncomment the ```writeln( "'Counter' is ", Counter );``` 
line and compiler says


```
/home/antonio/Devel/topbrokers/whatsapp-srv/admin/x.d(12): 
Error: function `x.Counter(int nextValue)` is not callable 
using argument types `()`
/home/antonio/Devel/topbrokers/whatsapp-srv/admin/x.d(12):  
  too few arguments, expected 1, got 0

```

I understand the problem with UFCS (``next`` is not using UFCS 
because it is a delegate defined in the own main() function,  
and ``Counter``` without () is treated as a function call 
because it is UFCS eligible )



`writeln( "'Counter' is ", Counter );`

this code is actually internally looks like this

`writeln( "'Counter' is ", Counter() );`

if you meant to take the function/delegate and not invoke try 
`&Counter` instead, otherwise it expects the parameters.


- What is the way to do ```writeln``` work with ```Counter``` 
function the same way it works with ```next``` function?


Sorry, that's too confusing and I have no idea what you mean, 
maybe if you can explain what you are trying to achieve someone 
might be able to help you.


Re: What is :-) ?

2023-11-20 Thread evilrat via Digitalmars-d-learn

On Monday, 20 November 2023 at 09:44:32 UTC, Antonio wrote:


- Why writeln doesn't treat ```next``` and ```Counter``` the 
same way?  (I think I understand why, but it shows a "low" 
level difference of something that syntactically is equivalent)


- What is the way to show Counter signature using ```writeln``` 
(if possible)?




I found no way to tell compiler that I don't want to call Counter 
and instead want to take the function itself, but closest thing 
is just to take the string representation at compile time (same 
as used in pragma msg) and pass it to writeln instead of Counter.


I guess this is one of these bif oof moments with UFCS, a 
function returning a (parameterless) function.


Note that in most cases you should never make runtime decisions 
on .stringof value as it is not standardized.



```
//pragma(msg, typeof(Counter)); // pure nothrow @safe int 
delegate() pure nothrow @nogc @safe(int nextValue)

enum f = typeof(Counter).stringof; // same string as above
writeln( "'Counter' is ", f);
```

Of course this works too
`writeln( "'Counter' is ", typeof(Counter).stringof);`




Re: What is :-) ?

2023-11-20 Thread evilrat via Digitalmars-d-learn

On Monday, 20 November 2023 at 16:09:33 UTC, Antonio wrote:


Is there any way to force D compiler to treat this 
"createCounter" declaration as **delegate** instead of 
**function**?


```d
  auto createCounter = (int nextValue) => () => nextValue++;
```


generally there is a way to tell the compiler specifically that 
you want a delegate or a function, and additionally there is 
`toDelegate` function from std.functional that could be useful in 
some cases.


https://dlang.org/phobos/std_functional.html#toDelegate


the syntax for specifying delegate/function is smth like this, 
IIRC return type can be omitted but for reference I write it here 
as auto.


```d
// this is a function returning a delegate
auto createCounter(int nextValue) => auto delegate() => 
nextValue++;


// this is a function returning a function
auto createCounter(int nextValue) => auto function() => 
nextValue++;

```


Re: [vibe] statically precompile some JS libs into an app binary

2023-12-24 Thread evilrat via Digitalmars-d-learn
On Friday, 22 December 2023 at 19:55:07 UTC, Dmitry Ponyatov 
wrote:
It is possible to statically precompile some JS libs and media 
fragments into an app binary?


My colleagues asks me to distribute app as a single standalone 
executable if it is possible, and maybe few millisecond of page 
load can be saved due to serving some assets from RAM.


Sure, try enum with import expression.

https://dlang.org/spec/expression.html#import_expressions

```d
enum myEmbebbedAsset = import("somefile.jpg");

// somewhere else for example in HTTP response handler
res.write(cast(ubyte[]) myEmbeddedAsset);
```

That enum will have that asset embedded in your executable.

It is used in conjunction with -J flag (string imports paths in 
dub) to tell where to find file, due to security considerations 
random files from unknown location are disallowed.


Just keep in mind that enum has some quirks in some cases where 
enum array access will allocate every time you access it, you can 
probably avoid this by using `immutable` or just `__gshared` 
variable.


Re: [vibe] what's wrong with linking time of vibe applications?

2023-12-24 Thread evilrat via Digitalmars-d-learn
On Friday, 22 December 2023 at 19:12:14 UTC, Dmitry Ponyatov 
wrote:

D lang noted as having a very fast compilation time.

Playing with tiny web-interface apps I found that modern 
versions of dmd & vibe has such a fast compiling but a very 
long executable linking time.


Something like 2-3 seconds of compiling stage (with vibe 
prebuilt), and 24 seconds of total build time




Welcome to template bloat hell.

IIRC diet templates is very template heavy, it makes tons of (D) 
template instantiations and the linker has a lot of work because 
of that. It is even worse with LDC.


If there is runtime diet parser(which I doubt) instead of default 
`render!` template you can move diet to it to save on compile 
time.




Re: Less verbose or at least "higher level" 2D game engines for Dlang.

2023-12-29 Thread evilrat via Digitalmars-d-learn

On Saturday, 30 December 2023 at 00:47:04 UTC, Agent P. wrote:

Hello everyone,

I'm looking for a 2D game engine for Dlang that offers 
flexibility but has a high-level interface, preferably less 
verbose. Although I've explored options on GitHub and in 
general, I haven't found something that exactly fits what I 
need.


Often the recommendations mention SFML, SDL or OpenGL (obvious 
links), but I would like to consider those options only after 
exploring engines with less verbose APIs.


I don't need much, I'm just looking for suggestions for engines 
that meet these criteria. Does anyone have any recommendations?


Thank you for your time.


There is godot-dlang, while it is not a D engine but just 
bindings, the Godot itself is a full featured engine including 
both 2D and 3D, it has UI framework and editor too.


I haven't even heard of any other D engines with editor btw, but 
unless you are need something minimal to make a basic one screen 
game with minimal build size it is a nice feature to have.





Re: Help optimize D solution to phone encoding problem: extremely slow performace.

2024-01-17 Thread evilrat via Digitalmars-d-learn

On Wednesday, 17 January 2024 at 07:11:02 UTC, Renato wrote:


If you want to check your performance, you know you can run the 
`./benchmark.sh` yourself?


Out of curiosity I've tried to manually run this on Windows and 
it seems that Java generator for these numbers files is "broken", 
the resulting count or print runs fine for both Java and D 
versions provided in your D branch, but fails with generated 
files.


D version complains about bad utf8 encoding.
I've opened the generated file in text editor and it is UTF-16 
(little-endian with BOM).


Tried with adoptium jdk 17 and 21 (former openjdk), but I guess 
it doesn't matter since UTF-16 is default on Windows.


Re: Help optimize D solution to phone encoding problem: extremely slow performace.

2024-01-17 Thread evilrat via Digitalmars-d-learn

On Wednesday, 17 January 2024 at 07:06:25 UTC, Renato wrote:
On Tuesday, 16 January 2024 at 22:15:04 UTC, Siarhei Siamashka 
wrote:

On Tuesday, 16 January 2024 at 21:15:19 UTC, Renato wrote:

It's a GC allocations fest. Things like this make it slow:

```diff
 {
-string digit = [digits[0]];
+string digit = digits[0 .. 1];
 words.insertBack(digit);
```


I was under the impression that `[digits[0]]` would just use a 
stack allocation??


The profiler does not show any GC anymore, are you sure it's a 
"GC allocations fest"???




nah, you are allocating new array out of single digit while the 
latter is just takes a slice.


there is 'scope' storage specifier for when you know your 
variable won't escape the scope to place it on stack (works for 
classes too), but I'm not sure if it will work with array.


`scope string digit = [digits[0]];`


Re: Help optimize D solution to phone encoding problem: extremely slow performace.

2024-01-17 Thread evilrat via Digitalmars-d-learn

On Wednesday, 17 January 2024 at 10:43:22 UTC, Renato wrote:

On Wednesday, 17 January 2024 at 10:24:31 UTC, Renato wrote:


It's not Java writing the file, it's the bash script 
[`benchmark.sh`](https://github.com/renatoathaydes/prechelt-phone-number-encoding/blob/master/benchmark.sh#L31):


```
java -cp "build/util" util.GeneratePhoneNumbers 1000 > 
phones_1000.txt

```



Perhaps using this option when running Java will help:

```
java -DFile.Encoding=UTF-8 ...
```


I've used powershell env var to set output to utf8, D version now 
works but java doesn't.


```
java -Xms20M -Xmx100M -cp build/java Main print words-quarter.txt 
phones_1000.txt
Exception in thread "main" 
java.lang.ArrayIndexOutOfBoundsException: Index 65485 out of 
bounds for length 10

at Trie.completeSolution(Main.java:216)
at Trie.forEachSolution(Main.java:192)
at PhoneNumberEncoder.encode(Main.java:132)
at Main.lambda$main$1(Main.java:38)
at 
java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184)
at 
java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:179)
at 
java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197)
at 
java.base/java.util.Iterator.forEachRemaining(Iterator.java:133)
at 
java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1939)
at 
java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:509)
at 
java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499)
at 
java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
at 
java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
at 
java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at 
java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:596)

at Main.main(Main.java:38)
```


Re: Help optimize D solution to phone encoding problem: extremely slow performace.

2024-01-17 Thread evilrat via Digitalmars-d-learn

On Wednesday, 17 January 2024 at 11:20:14 UTC, Renato wrote:


That means the input file is still not ASCII (or UTF-8) as it 
should. Java is reading files with the ASCII encoding so it 
should've worked fine.


It seems that it is only works with ASCII encoding though.


Re: Help optimize D solution to phone encoding problem: extremely slow performace.

2024-01-19 Thread evilrat via Digitalmars-d-learn

On Friday, 19 January 2024 at 16:55:25 UTC, ryuukk_ wrote:


You do hash map lookup for every character in D, it's slow, 
whereas in Rust you do it via pattern matching, java does the 
same, pattern matching



Yet another reason to advocate for pattern matching in D and 
switch as expression


There is another important difference, i quickly looked up D 
associative array implementation and the search looks like 
nlog(n) complexity with plain loop iteration of hashes, whereas 
rust's implementation is using "swisstable" algorithm 
implementation that has packed SIMD optimized lookups, this is 
likely where the 3x speed difference comes from.


Tried to look up rust implementation and it is SOOO generic that 
I was unable to decipher it to find the actual key search and 
stores.


Anyway here is an interesting article about rust implementation
https://faultlore.com/blah/hashbrown-tldr/


Re: Question on shared memory concurrency

2024-03-04 Thread evilrat via Digitalmars-d-learn

On Monday, 4 March 2024 at 16:02:50 UTC, Andy Valencia wrote:
On Monday, 4 March 2024 at 03:42:48 UTC, Richard (Rikki) Andrew 
Cattermole wrote:

A way to do this without spawning threads manually:
...


Thank you!  Of course, a thread dispatch per atomic increment 
is going to be s.l.o.w., so not surprising you had to trim the 
iterations.


Bug I still hope to be able to share memory between spawned 
threads, and if it isn't a shared ref of a shared variable, 
then what would it be?  Do I have to use the memory allocator?


There is `__gshared` type qualifier, but unlike plain `shared` it 
is up to you to ensure valid concurrency access as stated in the 
docs.


https://dlang.org/spec/const3.html#shared_global


Re: How to check that import module will succeed?

2019-07-25 Thread evilrat via Digitalmars-d-learn

On Friday, 26 July 2019 at 03:42:58 UTC, Andrey Zherikov wrote:
Is there a way to check whether some module, say "foo", is 
available for import before doing "import foo"?


I did some really retarded utility like this in the past, worked 
for me, but I can't say it is that well tested and there might be 
a better way (after all it just assumes that template 
instantiation failure can only mean there is no such module), so 
in short template allowed to fail, and we check if it is failed 
or not to test if desired module exists. Don't remember if static 
is really necessary or you can just return directly.


bool isModuleAvailable(alias modName)() {
mixin("import " ~ modName ~ ";");
static if (__traits(compiles, mixin(modName).stringof))
return true;
else
return false;
}

// use like this
static if (__traits(compiles, isModuleAvailable!"mymod" ))
import mymod;


Re: How to check that import module will succeed?

2019-07-26 Thread evilrat via Digitalmars-d-learn

On Friday, 26 July 2019 at 14:56:37 UTC, Andrey Zherikov wrote:


Even without static if I get the same result:
mixin template my_import(alias modName)
{
mixin("import " ~ modName ~ ";");
}
mixin my_import!"mymod";
pragma(msg,fullyQualifiedName!(myfunc));   // Error: 
undefined identifier myfunc

pragma(msg,fullyQualifiedName!(mymod.myfunc)); // mymod.myfunc

If I understood template mixin doc correctly this happens 
because of "The declarations in a mixin are placed in a nested 
scope". So is there a way to make two use cases above to work 
the same way, i.e. "myfunc" to be available without "mymod." 
prefix?


Exactly. Because of scoping rules mixin templates are nearly 
useless, there was a lot of frustration/criticism on them, but 
this is by design - to not turn them in macro hell like in C.
My opinion is that if core team are so picky about explicitness 
they should also provide a way to explicitly mix into the current 
scope, but of course I'm just yet another stranger here.


So you can do string mixin instead, however it requires more 
labor, and usually one has to keep in mind all intricacies of the 
features used which quickly leads to complexity combinatory 
explosion.


But whatever... With helper function above you can try this

@property string my_import(alias mod)()
{
return
	"static if (__traits(compiles, isModuleAvailable!\"" ~ mod ~ 
"\"))" ~

"{" ~
" mixin(\"import \",\"" ~ mod ~ "\", \";\"); " ~
"}";
}

// should import into current scope
mixin(my_import!"std.string");


Re: Is it possible to disallow import for certain functions?

2019-07-27 Thread evilrat via Digitalmars-d-learn

On Saturday, 27 July 2019 at 12:48:12 UTC, BoQsc wrote:


I seem to be doing something wrong, the result is the same.
otherFile.d(8): Error: only one main, WinMain, or DllMain 
allowed. Previously found main at mainFile.d(11)





private version = otherMain;
version(otherMain) {
void main(){
writeln("Interesting");
}
}


Of course. When you import that module "version = ..." is likely 
still evaluated and it enables that second main. Either move it 
to yet another module(and that's just masks the problem) or use 
command-line parameter to toggle which one to use.


Re: How the hell to split multiple delims?

2020-02-16 Thread evilrat via Digitalmars-d-learn

On Sunday, 16 February 2020 at 09:57:26 UTC, AlphaPurned wrote:


1>Test.d(31): error : template ...
1>Test.d(61): error : template ...
1>Test.d(66): error : cannot implicitly convert expression `l` 
of type `immutable(char)` to `string`

1>Test.d(31): error : template ...
1>Test.d(79): error : template ...



You can clearly see it all starts with 'template' except your 
code. Did you write any templates? No? Well then.


How do you think library writers can point you out to the 
problem? What if you do template with template? BOOM.


Don't get me wrong I'm not protecting the existing order, but.. 
Have you ever thinked about why so much 'junk' for templates? If 
not, here is a little comparison - whenever you use templates 
you've stepping into completely dynamic typing territory. Have 
you ever written any JS or Python code and then tried to make 
sense out of it when refactor? Yep, same shit here. Compiler have 
no idea what nonsense is all this junk, until you use it. And 
this is awesome because in dynamic typing languages you won't 
know it happens until you run it!





This is very annoying. It talks about regex, CTRegexWrapper...

so much BS for such a simple error. To me these error messages 
are counter productive. It's just a wall of crap that I have to 
sift through and analyze and then reason to the bug.




(no offence, you can ignore this)
so ignorant, much attitude, such wow...

You won't believe it but sifting through and analyze is just but 
regular programming stuff.




Re: AA code 50x slower

2020-02-16 Thread evilrat via Digitalmars-d-learn

On Sunday, 16 February 2020 at 12:57:43 UTC, AlphaPurned wrote:

template AA(string[] S)
{
auto _do() { int[string] d; foreach(s; S) d[s] = 0; return d; }
enum AA = _do;
}



My best guess is that enum arrays(except strings) and AA's are 
instantiated every time you access them.

This is especially bad with loops.

Probably you want static or module level variable instead.
Module level AA's can't have compile time initializer, however 
you can do initialization with module constructor instead.

https://dlang.org/spec/module.html#staticorder


Re: AA code 50x slower

2020-02-16 Thread evilrat via Digitalmars-d-learn

On Monday, 17 February 2020 at 02:18:15 UTC, AlphaPurned wrote:


But the input to the AA is static, it never changes. I thought 
D would essentially treat it as a constant and compute it once?


(I'm only using the AA in one place but it is in another 
template that is used twice. I can't imagine it would couldn't 
figure out how to optimzie it, I'm feeding it a constant so...)


The reason is that AA is a runtime-dependent construct, but it's 
not available at compile time, nor that there is some known ahead 
of time interface to it(ok, not exactly but something like that), 
so instead it does this whenever AA enum is referenced.


See Steven's code above, it might work like you thought however 
despite whatever input it will likely have exactly one variant of 
it because instantiated on string[] type, if that's the case and 
this is not what you wanted you might try tuple parameter instead 
of string[].


Re: dub libs from home directory on windows

2020-03-18 Thread evilrat via Digitalmars-d-learn

On Wednesday, 18 March 2020 at 19:53:58 UTC, jmh530 wrote:
On Wednesday, 18 March 2020 at 15:10:52 UTC, Виталий Фадеев 
wrote:

On Wednesday, 18 March 2020 at 13:52:20 UTC, Abby wrote:


I cannot build my app, so I was wondering if there is some 
clever way to solve this without hardcoded path to my profile 
name.


Thank you very much for your help.


I see, you want without hardcoded path...


I usually something like ./folder/file.extension to avoid a 
hardcoded path.


I also recommend taking a look at some other dub files to get a 
sense of how others do it.


Even better option is to just use "libs" section as usual(no 
paths, just names) and set environment variable specific to your 
machine prior to build.
For MS linker it is 'LIB' with semicolon as delimiter, for Linux 
it is 'LIBRARY_PATH'.


This way it is much more 'portable' and CI friendly, though it 
definitely will add confusion and 'annoyance' for first time 
users.


example batch:

  set LIB=C:\someproject\libs;E:\superduper\lib64
  dub build



Re: A question about C++ interop

2020-03-28 Thread evilrat via Digitalmars-d-learn

On Saturday, 28 March 2020 at 19:14:38 UTC, YD wrote:


Hi, now I have a further question: when the C++ class A 
actually has a method that looks like


virtual void get_info(std::string &s) const = 0;

in order to preserve the virtual function table layout (I found 
that if I omit this function completely in the D declaration, 
and try to use a virtual member function originally defined in 
C++ after this function, the result is core dump), even if I 
don't use this function, in the D file I have to put in line 
like this


abstract void get_info(basic_string!(char) s) const;


Yes, ABI implies that. If you don't use it at all you can just 
put a dummy entry like in the following code, otherwise it tries 
to call wrong method.


In many cases it will just crash, but this also could introduce 
very hard to find bugs when vtable is changed due to class 
changes, and the method that you were trying to call landed in 
vtable on another method with same signature - Imagine having API 
like Database class and instead of dump database it will drop all 
tables... phew.


 ...
 // other methods
 void vtable_dummy01() {} // or abstract if it's abstract
 // other methods
 ...


When I try this on Linux (Ubuntu 18.04), the compiler (both dmd 
and ldc2) will complain about "std::__cxx11::basic_string is 
not yet supported", but otherwise the code compiles and links 
correctly, and can run without problem.


STL bindings is unfinished, and don't expect it to be done any 
time soon. Tiny fractions of it might be present in Phobos (D 
standard library), but this work was done by few people who 
really needed that feature and it seems they are now too busy to 
continue that work.




So does this mean that there is no way I can interface to this 
C++ API in Windows? Thanks.


Same here, STL bindings is not yet finished. If you don't need 
that method specifically, just replace it with a dummy. Or make 
your own bindings.


Re: Link error undefined symbol: __imp__InterlockedIncrement@4 on windows

2020-04-10 Thread evilrat via Digitalmars-d-learn

On Thursday, 9 April 2020 at 14:07:10 UTC, Clayton Alves wrote:
I'm trying to compile my first hello world dub project, but 
when I run "dub" it spits this error:


lld-link: error: undefined symbol: __imp__InterlockedIncrement@4

Does anybody have any clues what is going on ?


This is from WinAPI, a very common one
https://docs.microsoft.com/en-us/windows/win32/api/winnt/nf-winnt-interlockedincrement

It seems shipped version of kernel32.lib is missing that symbol. 
If you don't mind installing Windows SDK and build tools this is 
usually the way to go.


On the other hand if you are specifically looking to use minimal 
as possible setup you could also try LDC (assuming you've been 
using DMD)


Re: Is it possible to store different subclasses in one array?

2020-04-12 Thread evilrat via Digitalmars-d-learn

On Monday, 13 April 2020 at 04:21:48 UTC, Leonardo wrote:


 foreach (ref gi; GameItems)
{
if (gi == Weapon)
gi.Attack()
}

How would it be?


Replying myself...

weapon = cast(Weapon) gi;
if (weapon !is null)
weapon.Attack()


can be simplified as:

if (auto weapon = cast(Weapon) gi)
weapon.Attack();


Re: Can I use Dlang in Qt5 instead C++ for develop Android Apps?

2020-04-13 Thread evilrat via Digitalmars-d-learn

On Monday, 13 April 2020 at 21:01:50 UTC, Baby Beaker wrote:
I want develop Android apps using Qt5. But C++ is very hard. I 
want to use Dlang becouse Dlang is very easy.


In theory nothing stops you from doing that. In practice however 
you have to deal with C++ anyway, how API matches ABI, and many 
more low level underlying things. You also need to know how your 
OS works.
Don't forget that you have to know the tools as well, dealing 
with Android means you will have to do cross-compilation. Must 
know how to use compilers, linkers and debuggers, and shell 
scripts as well as bonus.
Oh and don't forget that you have to make bindings to interface 
these 2 domains, and that requires knowledge of both D and C++.


So if you're too brave yet go ahead and try.


There was some Qt attempts such as this one 
https://code.dlang.org/packages/qte5
But since the last release was in 2016 it is probably no longer 
compiles, and I have no idea if it supports Android.


Re: Linker error under Ubuntu

2020-05-14 Thread evilrat via Digitalmars-d-learn

On Thursday, 14 May 2020 at 16:09:16 UTC, solidstate1991 wrote:
When I try to compile my own project under Ubuntu with dub, I 
get the following linker error:


/usr/bin/ld: .dub/obj/pixelperfectengine_pixelperfecteditor.o: 
undefined reference to symbol 'inflateEnd'
//lib/x86_64-linux-gnu/libz.so.1: error adding symbols: DSO 
missing from command line

collect2: error: ld returned 1 exit status
Error: /usr/bin/gcc failed with status: 1
/usr/bin/ldc2 failed with exit code 1.

I've checked for zlib and it was already preinstalled. I tried 
to install LLD, but that didn't help.


The latest version of my project found here: 
https://github.com/ZILtoid1991/pixelperfectengine


Um, pardon the stupid question, but did you just forgot to link 
it? I can't see a mention of it anywhere in both the old json and 
dub.sdl, and I don't see subpackages either. (does it links 
implicitly by the compiler?)


Also if it's digged up somewhere, another possibility is the link 
order issue(you need to put libs in order that adds linker 
symbols for previous libs to consume, for circular dependencies 
you can specify libs multiple times). The MS linker and LLVM 
linkers(not sure about GNU gold) does some work for you so you 
don't have to reorder libs most of the time.


Re: Linker error under Ubuntu

2020-05-15 Thread evilrat via Digitalmars-d-learn

On Friday, 15 May 2020 at 23:49:37 UTC, solidstate1991 wrote:


Dub should do the linking by itself.


How does it know what to link?



Re: `this` template params for struct not expressing constness.

2020-06-08 Thread evilrat via Digitalmars-d-learn

On Monday, 8 June 2020 at 07:35:12 UTC, adnan338 wrote:
Hi, as far as I understand, the `this` template parameter 
includes constness qualifiers as seen in 
https://ddili.org/ders/d.en/templates_more.html


To apply this I have this following struct:

module bst;

struct Tree(T) {
T item;
Tree!T* parent, left, right;

this(T item) {
this.item = item;
}

Self* searchTree(this Self)(auto in ref T item) const {
if (&this is null)
return null;
if (this.item == item)
return &this;
return (this.item < item) ? this.right.searchTree(item) 
: this.right.searchTree(item);

}
}

unittest {
auto text1 = "Hello", text2 = "World";

auto tree2 = Tree!string(text1);
assert(tree2.searchTree(text2) is null);
assert(tree2.searchTree(text1) !is null);

auto tree1 = Tree!int(4);
assert(tree1.searchTree(5) is null);
assert(tree1.searchTree(4) !is null);

}


When I run the unittest the compiler complains:

cannot implicitly convert expression &this of type 
const(Tree!string)* to Tree!string*


Run link: https://run.dlang.io/is/b76DND

Why does this happen?


If I correctly understand what you are trying to do the answer is 
- in D const is transitive (unlike the C++ where it isn't).


And in your searchTree() method you are basically trying to 
escape that constness. You can change the signature to return 
const(Self)*, or maybe add non-const overload depending on your 
needs.


Don't even think about casting away const with `return 
cast(Self*) &this;` as this UB in D, and it will bite you 
somewhere later because compiler might rely on const for 
optimization.




Re: Interfacing with C++ std::shared_ptr and std::unique_ptr

2020-06-09 Thread evilrat via Digitalmars-d-learn

On Wednesday, 10 June 2020 at 06:43:24 UTC, Andre Pany wrote:


Also, the C++ classes make use of templates. Is it still 
possible to call these

classes from D?


It should be, I did something similar and it worked. But it was 
quite some time ago so I don't remember exact situation and any 
details.


However you still be out of luck if the types you are trying to 
use is present in header only, since there is simply nothing to 
link with, so now you have to port whole template to D, or make 
dummy wrapper in C++ that forces the compiler to emit those 
symbols.


Same with ctor/dtors, if you have a class that is only used in 
some executable and not present in any of a .lib/.a form you're 
stuck. This is especially annoying with destructors because it 
renders the whole thing unusable without helper libraries that 
does new/delete in order to get the damn symbols emitted in 
object files to be able to link.


Re: Does std.net.curl: download have support for callbacks?

2020-06-11 Thread evilrat via Digitalmars-d-learn

On Thursday, 11 June 2020 at 06:05:09 UTC, adnan338 wrote:
I would like to set a callback for the `download()` function 
but I do not seem to find a way to add a callback to the 
procedure.


Let's say, for example I have a GtkD Widget called "pb" (short 
for progressBar).


I want to download a file from a url and when done, I want a 
callback to access pb and increase by a certain number.


The GtkD progress bar API:
https://api.gtkd.org/gtk.ProgressBar.ProgressBar.setFraction.html

Normally, If it was dependent on a button, I would do something 
like:


auto pb = new ProgressBar();
auto more = new Button("go-next", GtkIconSize.BUTTON);
more.addOnClicked(delegate void(Button _) {
if (activityMode.getActive()) // ignore this if 
condition

pb.pulse;
else
pb.setFraction(pb.getFraction + pb.getPulseStep);
});

But how can I do this with `download()`?


From the docs on download() method it has an optional connection 
reference

https://dlang.org/phobos/std_net_curl.html#.download


And connection has onProgress callback, you can add some global 
variable and update it using this callback.


Now of course another problem left up to you, not thread safe 
means you should expect the worst if you try to use the library 
from multiple threads, this is especially true for UI libraries 
as some OS implies some restrictions on UI interactions as well.


So you need to find relevant mechanism to do a event loop 
scheduling and update progress bar using it by feeding the values 
from somewhere else.


See https://dlang.org/phobos/std_net_curl.html#.HTTP under 
"Tracking progress: " example.

It turns out you might not need to use download() at all.

Pseudocode:

  // some global vars to track it
  size_t bytesTotal;
  size_t bytesReceived;

  // in your downloader thread
  auto http = HTTP();
  http.method = HTTP.Method.get;
  http.url = "http://upload.wikimedia.org/wikipedia/commons/"; ~
   "5/53/Wikipedia-logo-en-big.png";
  http.onReceive = (ubyte[] data) { bytesTotal = 0; bytesReceived 
= 0; return data.length; };

  http.onProgress = (size_t dltotal, size_t dlnow,
   size_t ultotal, size_t ulnow)
  {
bytesTotal = dltotal;
bytesReceived = dlnow;
return 0;
  };

  // somewhere in GTK do something like this, it is up to you to 
find out how to do this

  void check_dl_status()
  {
// here we are using globals that updates on another thread
auto progressPct = bytesTotal / bytesReceived;
progresBar.setPercent (progressPct);

if (progressPct < 1)
  event.publish (check_dl_status);
  }





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

2020-07-13 Thread evilrat via Digitalmars-d-learn

On Monday, 13 July 2020 at 09:34:35 UTC, zoujiaqing wrote:

I changed string to basic_string.

///  source/main.d
import std.stdio;
import core.stdcpp.string;

extern(C++)
{
class Canvas
{
@disable this();

static Canvas Create();

basic_string!ubyte Foo();

basic_string!ubyte Bar();
};
}

void main()
{
Canvas canvas = Canvas.Create();

writeln(canvas.Foo());

writeln(canvas.Bar());
}

Error ...

# dmd source/main.d Canvas.o -L-lstdc++ && ./main
[1]49078 segmentation fault  ./main


Putting std::string support aside there is another issue in this 
example. D has virtual by default semantic unlike C++.


One possible segfault reason is that because it tries to call non 
existing virtual method.


Marking those D methods 'final' should fix linking issues. Also I 
can't remember if extern(C++) is implicitly propagated to class 
methods so I would put extern(C++) in class body just to be sure.




Re: How to compile Windows exe files from this source

2020-08-09 Thread evilrat via Digitalmars-d-learn

On Sunday, 9 August 2020 at 19:04:07 UTC, Marc wrote:
I don't know much more about D than creating a 'hello world' 
exe file with the DMD Compiler

but I'm interested in using the eBay/tsv-utils binaries.
Unfortunately, the author didn't create any MS Windows binaries:
https://github.com/eBay/tsv-utils/releases

Does anyone know how to compile this code into MS Windows 
binaries?


Sure, assuming there is no external(i.e. C/C++ prerequisites) 
dependencies just clone it and run `dub build` from project 
folder in terminal.


Alternatively there is probably `dmd -run dub_build.d`(though you 
have to check out how to use it), and also makefiles which you 
could probably use with shell that comes with git or mingw.







Re: Getting Qte5 to work

2020-10-27 Thread evilrat via Digitalmars-d-learn

On Tuesday, 27 October 2020 at 11:46:02 UTC, Josh Dredge wrote:
Hi all, I'm completely new to D and while I'm not new to 
programming in general, I mostly do web development,


Welcome! If by web development you also have back-end programming 
then you should be like 50% know how desktop programming works.




I'm looking at learning D, but would like to stick with what I 
know on desktop in terms of event-driven GUI based applications.


Just an advice, Qte5 isn't well maintained, the other 
alternatives such as 'dlangui' also seems abandoned, so basically 
the only maintained UI library here is gtk-d, but there was 
recently a nice tutorial series written about it.


Though I admit I've kind of dropped from the D for the 6 months.

I have Visual D installed, as well as QtCreator and was hoping 
to be able to use Qt with D. I'm happy without any GUI builder 
for now, but still need a working GUI library! Qte5 looks fine 
but need to figure out how to implement it.


I've installed D in "C:\D" (Windows 10 x64).
I've installed Qte5 in "C:\D\Qte5".

Quite simply typing "import Qte5;" into the code doesn't work 
(module not found), and I'm not sure how to make sure the 
library is correctly installed and reference. Is there a setup 
guide? I found one on Youtube but it didn't really explain 
anything. What's the way to do it?




First, since you are already trying to work with C++ (Qt is a C++ 
framework after all) under the hood you will likely need to 
install MS build tools and Windows SDK, this will get you missing 
libraries and first-class support for building native binaries.


Now to the point - 'module not found' is a compiler message that 
tells you 'there were no such module in module search paths', 
with dmd you can point compiler to look for qte5 dir with -I flag 
(or recently -i to also build these), then you also need to pass 
built .lib OR .obj files for Qte5 that contains compiled code 
otherwise you'll see link errors.


So for building your code it is better (for now) to use 
'dub'(official build system & package manager, usually ships with 
compilers)



Let's just make a new dub project and add qte as dependency 
(since it's already on dub registry)


  - Let's create a new project in current working directory named 
MyAwesomeProject, just hit enter for all questions

$> dub init MyAwesomeProject

  - Now go to this folder
$> cd MyAwesomeProject

  - Clone qte5 repo to your project (or download and unzip)
$> git clone https://github.com/MGWL/QtE5

  - And let's add Qte5 dependency(btw you can see it here 
https://code.dlang.org/packages/qte5), note that it is completely 
unrelated with our cloned repo

$> dub add qte5

  - Now open your dub.json in your project and replace dependency 
path (we do this because it is semi-abandoned, and last published 
version was 4 years ago, even though there was some recent 
activity on master branch) so your dependency section should like 
this

"dependencies": {
"qte5": { "path" : "./QtE5" },
},

  - If you try to build it right now it will error, so we have to 
"fix" it, so go to QtE5 folder, open dub.json and remove 
'sourceFiles' section, it should build just fine without it.


  - Copy example code from QtE5/example/example.d and replace 
your source/app.d with it


  - Build using dub
$> dub build

  - Done! Now if you have Qt5 installed and present in you system 
%PATH% environment variable (or copied DLL's next to executable) 
I assume it should work. (since I don't have I can't test if it 
actually works)


  - (Optional) It is possible to (re)generate VisualD project 
after you modify your dub project configuration, (additionally it 
can take any other build options such as --arch or --config, but 
ultimately it generates exactly one variant of all possible 
arch/config flavors)

$> dub generate visuald

Where to get packages?
D packages and dub (note though that not everyone publish it 
here, some people have extra fancy stuff on their github/gitlab) 
- https://code.dlang.org/





Re: Iterating chars by Word

2020-11-12 Thread evilrat via Digitalmars-d-learn

On Friday, 13 November 2020 at 05:14:08 UTC, Виталий Фадеев wrote:

Is:
wchar[] chars;  // like a: "import 
core.sys.windows.windows;\nimport std.conv  : to;\n"


Goal:
foreach ( word; chars.byWord )
{
// ...
}


You can make your own range, however look at this function first 
(second example)

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

// 1) might need to cast your wchar[] to wstring first
// 2) also assumes that 'the word' is separated by whitespace
foreach( word; chars.splitter(' '))
{

}

or this one, which is a bit more smarter about what "the word" 
means

https://dlang.org/phobos/std_array.html#.split

import std.array : split;

wchar[] str = cast(wchar[]) "some random stuff blah blah"w;
foreach(w; str.split())
{
writeln(w);
}

Anyway in both cases using dmd -vgc flag shows no GC allocations 
done.


Re: Getting started with graphqld

2020-12-17 Thread evilrat via Digitalmars-d-learn

On Tuesday, 15 December 2020 at 16:25:29 UTC, Trustee wrote:


connect a basic vibe-d app to a graphql backend.



umm, what?
Did you mean write graphql backend using vibe.d?


Re: C++ or D?

2020-12-23 Thread evilrat via Digitalmars-d-learn

On Wednesday, 23 December 2020 at 18:03:56 UTC, frame wrote:


It's not the problem mentioned but I had to struggle with DLLs 
and D's Variant-type. The problem is that Variant uses TypeInfo 
which does not pass DLL boundaries correctly so that int != int 
in runtime even it's in fact a simple int.


If you need to exchange unknown data between a DLL and your 
application you need to get a workaround and cannot use that 
elsewhere settled nice feature. But it's a Windows specific 
issue - it works as expected on other systems.


Which is basically same as in C++, despite the fact it does have 
real working SO/DLL runtime's many large projects have their own 
RTTI implementation. LLVM has its own RTTI because standard type 
info is "inefficient", Unreal Engine has its own, IIRC Qt too has 
its own, etc...


Same thing with D Variant, some people say it is "inefficient"... 
so we ended up having multiple libraries.


Not saying anything about how good or bad all this, just the 
facts.


Re: Developing and running D GUI app on Android

2021-01-10 Thread evilrat via Digitalmars-d-learn

On Sunday, 10 January 2021 at 18:58:13 UTC, aberba wrote:
I'm looking to explore running a D application on Android based 
on Adams previous foundation work. However, I'm not familiar 
with the Android + D integration so I need some help.


Has any of you successfully done that? Could use a sample code 
or anything I can use to figure out how to start.


Android itself is just linux under the hood, however the launcher 
starts java process that fires up your activity class (main in 
native languages) from there you just call your native code and 
that's it.


This means
1) you need to build D shared lib
2) make java wrapper in activity to call your code
3) handle your events as if it's java

I did some work in the past for DlangUI[1], you can probably take 
the gradle project[2] with build scripts and the Activity class 
as the starting point, however I have no idea what does arsd libs 
with gui.


Also note that I did it for existing DlangUI code based on 
NativeActivity library which is deprecated for years now, and 
that's why you need proper java wrapper.


[1] https://github.com/buggins/dlangui/tree/master/android
[2] 
https://github.com/buggins/dlangui/tree/master/examples/android


Re: Developing and running D GUI app on Android

2021-01-11 Thread evilrat via Digitalmars-d-learn

On Monday, 11 January 2021 at 07:38:00 UTC, Elronnd wrote:

On Monday, 11 January 2021 at 06:26:41 UTC, evilrat wrote:
Android itself is just linux under the hood, however the 
launcher starts java process that fires up your activity class 
(main in native languages) from there you just call your 
native code and that's it.


It turns out that you don't strictly need the java wrapper.  
See https://github.com/cnlohr/rawdrawandroid


Sure whatever, just good luck handling IME input. It might be 
possible without any wrappers, though I'm unaware of any sane way 
to do it. I am not an android developer though.


Re: How build DCD on Windows?

2021-01-11 Thread evilrat via Digitalmars-d-learn

On Tuesday, 12 January 2021 at 00:35:41 UTC, Marcone wrote:
Hi, Someone can Help me build exe dcd server and client on 
WIndows? Step by step? Becouse the informations disponible is 
very hard to undestand.


Are you serious?
It's on the first page of their repo under the Setup section
https://code.dlang.org/packages/dcd

just clone the repo, open it up in terminal and run the 
following. it will produce two separate binaries for client and 
server. Yes, that's all.


dub build --build=release --config=client
dub build --build=release --config=server




Re: Collections in D

2021-01-13 Thread evilrat via Digitalmars-d-learn

On Wednesday, 13 January 2021 at 12:06:05 UTC, Roguish wrote:


What about sets?


There is no specific set container, they just implemented as 
generic algorithms over the ranges.


There is a section for set operations (std.algorithm.setops 
module).

https://dlang.org/phobos/std_algorithm.html


Re: How to debug D on Linux

2021-01-13 Thread evilrat via Digitalmars-d-learn
if you are looking for back trace someone recently posted a hint 
for linux where there is no back trace by default is to import 
core.sys.linux.backtrace or something that has back trace info 
and using it in exception handler for runtime to print the stack 
trace.

https://dlang.org/phobos/core_runtime.html#.defaultTraceHandler


On Wednesday, 13 January 2021 at 13:47:55 UTC, Roguish wrote:


One specific question I have is: what's the difference between 
-g and -debug and -d-debug?


no idea what is -d-debug, but -g will emit debug info for 
debugger, and -debug will turn on certain features such as 
contracts and asserts even in release builds.


Re: Why doesn't this work when the function is a static method?

2021-01-14 Thread evilrat via Digitalmars-d-learn

On Thursday, 14 January 2021 at 05:44:43 UTC, Jack wrote:
On Wednesday, 13 January 2021 at 17:21:23 UTC, Paul Backus 
wrote:


Member functions (including static ones) can't be called with 
UFCS.



 is this documented somewhere? Is this going to change?


It will stay as is.
It is somewhat vaguely described in p.7 under UFCS section in 
functions


https://dlang.org/spec/function.html#pseudo-member


Re: How can I specify flags for the compiler when --build=release in dub?

2021-01-15 Thread evilrat via Digitalmars-d-learn

On Friday, 15 January 2021 at 17:02:32 UTC, Jack wrote:

is this possible? if so, how?


You can add extra options for for platform and compiler, and IIRC 
for build type too.


For example like this for lflags, it might complain about the 
order so just follow the instructions.


"lflags-debug"
"lflags-windows-debug"
"lflags-linux-ldc2-release"
"lflags-windows-x86_64-dmd-debug"


Re: How can I create a Standalone Bundle Portable file application using Dlang?

2021-01-19 Thread evilrat via Digitalmars-d-learn

On Tuesday, 19 January 2021 at 11:10:25 UTC, Marcone wrote:

On Tuesday, 19 January 2021 at 06:25:31 UTC, Imperatorn wrote:

On Monday, 18 January 2021 at 19:42:22 UTC, Marcone wrote:
How can I create a Standalone Bundle Portable file 
application using Dlang?


Could you describe what you mean with "Bundle portable file 
application"?


All dependencies inside an exe file. Like Python Pyinstaller.


One possible way is to use import() operator to embed file into 
resulting artifact, then write it to disk in main or module ctor 
and load as usual.
note however you need to tell compiler about file lookup path (-J 
flag) or use dub string import path respectively.


  // compile time
  enum myEmbeddedFile = import("path/to/file");

  // pseudocode
  void main()
  {
// write file at runtime
write(cast(ubyte[]) myEmbeddedFile, "./myfile.ext");

// or use directly from memory
writeln(myEmbeddedFile)
  }

this however not possible with implicit dynamic linking, though 
you still can use this approach if you do use LoadLibrary/dlopen 
yourself.


Re: How can I create a Standalone Bundle Portable file application using Dlang?

2021-01-24 Thread evilrat via Digitalmars-d-learn

On Sunday, 24 January 2021 at 11:44:04 UTC, Marcone wrote:


Qt5 dlls


Well, you are out of luck. It is doable, but...

Normally you would likely want to use static libraries and link 
them into your executable, with Qt license however it becomes 
problematic in pretty much any case, you still can embed them 
using import() and unpack to a temporary directory for manual 
loading without violating the license.


Another problem mentioned before is implicit dynamic loading 
where you link with special stub .lib file for automatic loading, 
which is more common in C++ due to symbol name mangling, that 
will not work because your code won't have a chance to run main().




Re: Dll crash in simplest case

2021-01-25 Thread evilrat via Digitalmars-d-learn

On Monday, 25 January 2021 at 11:30:45 UTC, Vitalii wrote:

On Monday, 25 January 2021 at 10:26:20 UTC, frame wrote:

[...]


Yes. I'm doing it whet add dll.d 
(https://wiki.dlang.org/Win32_DLLs_in_D) in compile line, it 
contents:

---
import core.sys.windows.windows;
import core.sys.windows.dll;

__gshared HINSTANCE g_hInst;

extern (Windows)
BOOL DllMain(HINSTANCE hInstance, ULONG ulReason, LPVOID 
pvReserved)

{
switch (ulReason)
{
case DLL_PROCESS_ATTACH:
g_hInst = hInstance;
dll_process_attach( hInstance, true );
break;

case DLL_PROCESS_DETACH:
dll_process_detach( hInstance, true );
break;

case DLL_THREAD_ATTACH:
dll_thread_attach( true, true );
break;

case DLL_THREAD_DETACH:
dll_thread_detach( true, true );
break;

default:
}
return true;
}
---


try replacing this with mixin SimpleDllMain (it initializes 
runtime for you IIRC). Runtime.LoadLibrary() is expected to call 
rt_init too, but Windows support for shared libs is too far from 
good.


Re: Why am I getting a dividing by zero error message

2021-01-28 Thread evilrat via Digitalmars-d-learn
On Thursday, 28 January 2021 at 18:37:37 UTC, Ruby The Roobster 
wrote:

Here is the output/input of the program:
Type in  data for an egg:
Width: 3
Hight: 2

object.Error@(0): Integer Divide by Zero

0x004023FE
0x0040CF9F
0x0040CF19
0x0040CDB4
0x00409033
0x00402638
0x75F86359 in BaseThreadInitThunk
0x77018944 in RtlGetAppContainerNamedObjectPath
0x77018914 in RtlGetAppContainerNamedObjectPath
Chicken:

Here is the source code:

import std.stdio;
import std.string;
void main(){
egg[1000] data;
data[0] = (new egg(0,0,"a"));
for(int i = 1;i<1000;i++)
{
int tempx;
int tempy;
string tempz;
int high = 0;
double highs = 0;
writeln("Type in  data for an egg:");
write("Width: ");
readf(" %d",&tempx);
write("Hight: ");
readf(" %d",&tempy);
write("Chicken: ");
tempz = readln();
data[i] = new egg(tempx,tempy,tempz);
for(int x = 0;x < i;x++)
{
int tempa;
int tempb;
double temp;
tempa = data[x].x;
if(tempa < 0)
tempa-=tempa;
tempb = data[x].y;
if(tempb < 0)
tempb-=tempb;


/*
x starts with 0, you are acessing data[x] which is set to 
egg(0,0,"a") and you get div by zero as a result. I see logic 
error, though I might be wrong because I haven't actually run 
your code.

*/


temp = tempa / tempb;
if(temp > highs)
{
highs = temp;
high = x;
}
}
tempx = data[high].x - data[i].x;
if(tempx < 0)
tempx-=tempx;
tempy = data[high].y - data[i].y;
if(tempy < 0)
tempy-=tempy;
}
}






Re: Class Allocators

2021-01-31 Thread evilrat via Digitalmars-d-learn

On Sunday, 31 January 2021 at 23:19:09 UTC, Kyle wrote:
My best guess right now is that both class allocators and the 
placement new syntax are deprecated, but if that's the case I 
would expect a deprecation message when I try to use that 
new(address) Type syntax whether there's a class allocator 
present or not. Any insight into this? Thanks.


Yes, just use emplace() insead of placement new.

GC-less allocations however is up to you, either malloc/free, 
std.experimental.allocator or any other way. You can make your 
own smart pointer struct to handle this automatically, or better 
use community packages such as 'automem'.


As for the message it is possible that this part of the reference 
compiler was already passed deprecation period and should be 
removed but was completely forgotten.


https://dlang.org/phobos/core_lifetime.html#.emplace



Re: Can change vtbl record at runtime ?

2021-02-03 Thread evilrat via Digitalmars-d-learn

On Wednesday, 3 February 2021 at 08:26:05 UTC, Max Haughton wrote:
On Wednesday, 3 February 2021 at 05:30:37 UTC, Виталий Фадеев 
wrote:

Possible to change the vtbl record at runtime ?
Has functional for update vtbl records ?


Do you mean "Can I set onSuccess" at runtime? The virtual 
tables are relied upon by the compiler so I wouldn't play with 
them.


Not to mention that compiler can optimize away virtual calls if 
it can determine final type on call site.


Re: Is there other way to do that?

2021-02-15 Thread evilrat via Digitalmars-d-learn

On Monday, 15 February 2021 at 07:26:56 UTC, Jack wrote:
I need to check if an instance is of a specific type derived 
from my base class but this class has template parameter and 
this type isn't available at time I'm checking it. Something 
like:




Non-templated interface/base class is probably the only way I'm 
aware of, it is also how it is usually done with C# generics 
where needed for the same reason.


Even though typeid() knows the type I have no idea how to use it 
that way.



Interface adds 1 pointer to classinfo or vtbl, so it is increases 
instance size a bit.


```
import std;

class B { }
class A(T) : B { }
class X : B { }
class Z : B { }

interface IA {}
class AA(T) : B, IA {}

void main()
{
writeln(__traits(classInstanceSize, AA!void)); // prints 24
writeln(__traits(classInstanceSize, A!void)); // prints 16
}

```




Re: is it posible to compile individual module separately?

2021-02-16 Thread evilrat via Digitalmars-d-learn

On Tuesday, 16 February 2021 at 07:01:53 UTC, bokuno_D wrote:

i run "dub build" on it. but OOM kill the compiler.
-
is there a way to reduce memory consumtion of the compiler?
or maybe third party tool? alternative to dub?


Assuming you are using DMD, there is -lowmem switch to enable 
garbage collection (it is off by default for faster builds)


open dub.json, add dflags array with -lowmem, something like this 
line:


   "dflags": [ "-lowmem" ],

then build normally, if you have gdc or ldc dub might pick first 
compiler in %PATH%, compiler can be selected with --compiler 
option


   dub build --compiler=dmd


Re: DUB is not working correctly

2021-02-24 Thread evilrat via Digitalmars-d-learn

On Wednesday, 24 February 2021 at 16:13:48 UTC, Maxim wrote:
Hello, I have problems with working in dub environment. If I 
try to init my project with 'dub init', all needed files will 
be created successfully. However, when I run 'dub run', the 
manager gives me an error:


'Configuration 'application' of package application contains no 
source files. Please add {"targetType": "none"} to its package 
description to avoid building it.
Package with target type "none" must have dependencies to 
build.'


If I set targetType in dub.json to "none", the only message:
 'Package with target type "none" must have dependencies to 
build.'


will remain. When I set targetName to "app" or any other name, 
the problem will appear again with the same message above. I 
flicked through many forums and videos how to correctly install 
dub, and nothing helped.


I am using dub 1.23.0 built on Sep 25 2020 on Windows 10 x64. 
Will be very thankful for your help!


Doesn't seem like an installation problem.

Could you post your dub.json contents and describe what you are 
trying to achieve?


Do you have your source files in 'src' or 'source' folder next to 
the dub.json file? If not, you need to tell dub to treat any 
other non conventional folder as source location.


Re: DUB is not working correctly

2021-02-24 Thread evilrat via Digitalmars-d-learn

On Wednesday, 24 February 2021 at 16:46:20 UTC, Maxim wrote:


Sure, here are dub.json contents:
{
"authors": [
"Max"
],
"copyright": "Copyright © 2021, Max",
"description": "A minimal D application.",
"license": "proprietary",
"dependencies": {
"dsfml": "~>2.1.1"
},
"targetType": "none",
"targetName": "app",
"name": "test"
}

I just want to run it by typing 'dub run'. But the error 
message says that I need to set targetType to none, add 
targetName and dependencies for it.




ok, you don't need targetType in this case, setting it to none 
means it will do nothing.


the original message likely related to dsmfl which haven't been 
updated since 2016, maybe you can try another package, for 
example bindbc-smfl (there is older 'derelict' series, and 
'bindbc' series which is newer and recommended over derelict)



https://code.dlang.org/packages/bindbc-sfml



Re: DUB is not working correctly

2021-02-24 Thread evilrat via Digitalmars-d-learn

On Wednesday, 24 February 2021 at 17:45:56 UTC, Maxim wrote:


Unfortunately, I tried bindbc-sfml package but the problem is 
still existing. I also started a new project and without any 
changes ran it but the result was the same. Anyway, thank you 
so much for your help!


does it works for an empty project created with 'dub init' from 
terminal?


Re: DUB is not working correctly

2021-02-26 Thread evilrat via Digitalmars-d-learn

On Friday, 26 February 2021 at 18:20:38 UTC, Maxim wrote:

On Friday, 26 February 2021 at 17:57:12 UTC, ryuukk_ wrote:

"targetType": "executable",

and it should just run using "dub run"


Unfortunately, the problem remains :/


Looks like something specific to your machine.

The last thing I could think of is to run dub with -v flag 
(verbose mode), look for all steps performed and check the output 
for anything that potentially could cause a failure.
Could be related to paths with spaces, path with non-ascii 
symbols, antivirus software, FS permissions, missing C++ SDK's 
and runtime libs, compiler toolchain installation, basically 
anything...


Re: How can I make this work?

2021-02-27 Thread evilrat via Digitalmars-d-learn

On Sunday, 28 February 2021 at 07:05:27 UTC, Jack wrote:
I'm using a windows callback function where the user-defined 
value is passed thought a LPARAM argument type. I'd like to 
pass my D array then access it from that callback function. How 
is the casting from LPARAM to my type array done in that case?


for example, I need something like this to work:

int[] arr = [1, 2, 3];
long l = cast(long) cast(void*) arr.ptr;
int[] a = cast(int[]) cast(void*) l;


Should already work like that. Just be aware that array can be 
garbage collected if no references for it are kept somewhere else 
between set callback and the actual call, otherwise you can get 
some random garbage.


Also be aware that such casts 99% basically a speculation, there 
is no guarantee that returned data is actually an int[].




Re: Shared library module system with dub

2021-03-01 Thread evilrat via Digitalmars-d-learn

On Tuesday, 2 March 2021 at 04:26:52 UTC, Pillager86 wrote:

On Tuesday, 2 March 2021 at 04:13:31 UTC, Pillager86 wrote:

On Tuesday, 2 March 2021 at 03:42:14 UTC, Pillager86 wrote:
Update: the dub "dynamicLibrary" target option is busted on 
Windows and does not build anything at all. This should be 
filed as a bug.


Update again: I got the Windows DLL to build and run without 
crashing, but I don't know how to put specific platform 
options in dub. I need "dflags" "-defaultlibrary=phobos2" or 
something on Linux but not Windows.


Try this (for dub.json)

"dflags-linux": ["-defaultlibrary=phobos2"]

For platform/architecture/compiler specific variants just add 
suffix like this, also works with lflags, and I guess pretty much 
any other options.


"dflags-linux" : ["specific flags for linux"]
"dflags-windows" : ["specific flags for windows"]
"dflags-windows-dmd" : ["more flags if building with dmd"]
"dflags-windows-dmd-x86" : ["even more flags if building for x86 
using dmd"]


Also, what do you do if the shared library needs to refer to 
types in the main static library?



You need to link it with your DLL, this will however will create 
lots of duplicated symbols in your executable.


In most cases this is undesireable, so instead one will usually 
put all common stuff into DLL and share across main executable 
and other DLL's that relies on it.


On Windows however DLL support is unfinished, so you are stuck 
with hacks and/or static libs option.




Re: Can't I allocate at descontructor?

2021-03-04 Thread evilrat via Digitalmars-d-learn

On Friday, 5 March 2021 at 05:31:38 UTC, Jack wrote:
The following code returns a memory error. I did notice it did 
happens whenever I did a memory allocation. Is this not 
possible in the descontrutor? if so, why?




GC prohibits allocation during collection, since this dtor is 
likely called by GC this is what happens.


If you REALLY need this just allocate using other mechanisms.


Re: Workaround to "import" an exception from a DLL

2021-03-14 Thread evilrat via Digitalmars-d-learn

On Sunday, 14 March 2021 at 09:35:40 UTC, frame wrote:


// this returns null in the program (but works in a debugger 
watch):

MyExceptionObj imported = cast(MyExceptionObj)e;

// this actually works:
MyExceptionObj imported = cast(MyExceptionObj) cast(void*)e;





Is there are way to copy the exception data in a new Throwable 
instance that can be thrown from the current context? Or can 
the runtime be tricked by overwriting the TypeInfo in memory? 
(I don't know exactly what the actual problem is.)


As a workaround maybe you could introduce special 
DLLWrapperException with reference to original exception using 
cast hack?


The problem is that TypeInfo is not shared on Windows, which is 
actually roots deeper in the other problems with "sharing".
Unfortunately I cannot provide you with details, but this 
situation is well known long standing issue.


From what I understand it is such a mess because D 
compiler/linker doesn't merge multiple symbols in running program 
which is how it basically works in C++ where DLL's works "as 
expected".


Re: Is there an easy way to convert a C header to a D module?

2021-03-14 Thread evilrat via Digitalmars-d-learn

On Monday, 15 March 2021 at 02:43:01 UTC, Tim wrote:

On Monday, 15 March 2021 at 02:03:09 UTC, Adam D. Ruppe wrote:

On Monday, 15 March 2021 at 01:53:31 UTC, Tim wrote:
I'm needing to use a c/c++ library in a D program and I'm 
struggling with creating a binding as it seems like an 
enormous amount of regex modifications. Is there an existing 
program that can create most if not all of a binding for me?


https://github.com/jacob-carlborg/dstep

That does most of it, then you fix it up with some regex or 
whatever to finish the job.


Seems pretty good. Does it work on c++ stuff too?


(shameless plug) You can try my crappy generator[1] for C++

There is also dpp[2] which probably can convert C++ decls to D

[1] https://github.com/Superbelko/ohmygentool
[2] https://code.dlang.org/packages/dpp


Re: WinUI 3

2021-03-15 Thread evilrat via Digitalmars-d-learn

On Monday, 15 March 2021 at 16:41:08 UTC, Imperatorn wrote:

Could D be used with WinUI 3?

https://docs.microsoft.com/en-us/windows/apps/winui/winui3/

Would the win32metadata help? 🤔


I've seen some slides about WinUI 3 future directions and roadmap 
but haven't tried it yet.
Probably it will be PITA to use it right now in anything not .NET 
because of some core dependencies (IIRC some core stuff is in 
.NET), but plans have mentions it will be possible to use with 
ANY language closer to release date somewhere in Q3 2021.


But if it can be done using C++/WinRT right now then it is highly 
likely this will be possible to do it in D as well.


As for WinRT stuff there was some tools and bindings done by 
webfreak.

https://github.com/WebFreak001/dwinrt2
and/or
https://github.com/WebFreak001/dwinrt


Re: How to declare "type of function, passed as an argument, which should have it's type inferred"? (or if D had an "any" type)

2021-03-29 Thread evilrat via Digitalmars-d-learn

On Monday, 29 March 2021 at 15:13:04 UTC, Gavin Ray wrote:
Brief question, is it possible to write this so that the "alias 
fn" here appears as the final argument?


  auto my_func(alias fn)(string name, string description, auto 
otherthing)


The above seems to work, since the type of "fn" can vary and it 
gets called inside of "my_func", but from an ergonomics point 
I'd love to be able to put the function last and write it 
inline:


  my_func("name", "description", "otherthing", (x, y, z) {
auto foo = 1;
return foo + 2;
  })


Currently I am calling it like:

  auto some_func = (x, y, z) {
auto foo = 1;
return foo + 2;
  };

  my_func!some_func("name", "description", "otherthing");

Which is fine, it's just that from a readability perspective it 
doesn't really allow for writing the function inline and you 
need to declare it separately.


Not a huge deal, just learning and thought I would ask =)

Thank you!


Also with delegates (lazy), you get the type checks however you 
must have to declare parameters on call site, which can be PITA 
in the future when doing refactoring will be necessary.


Better plan ahead as the number of changes will explode when you 
make quite a number of these and decide to change params/returns.


```
  import std.stdio;

  void my_func(T, XS)(string a, string b, string c, lazy T 
function(XS)[] t...)

  {
// call function, just the first one, can call all of them as 
well

t[0](a);

// can get the result too, mind the future refactoring needs 
tho

// T res = t[0]();
  }

  void main()
  {
my_func("name", "description", "otherthing", (string x) {
  writeln(x);
  return x;
});

// no function, compile error
// my_func("name", "description", "otherthing");
  }
```


Re: How to declare "type of function, passed as an argument, which should have it's type inferred"? (or if D had an "any" type)

2021-03-29 Thread evilrat via Digitalmars-d-learn

On Monday, 29 March 2021 at 17:52:13 UTC, Gavin Ray wrote:

Trying to read this function signature:

void my_func(T, XS)(string a, string b, string c, lazy T 
function(XS)[] t...)


Does this say "Generic void function 'my_func', which takes two 
generic/type params "T" and "XS", and is a function of type 
"string a, string b, string c", and..." (this is where it 
starts to get hazy for me):


How does one interpret/read this:

   lazy T function(XS)[] t...


A tuple of functions that takes XS argument(s) and returns T.

'...' part is a tuple/variadic arguments, however with function 
it is somewhat wacky and requires an array notation [], otherwise 
compiler treats it like a mere pointer for some reason, same with 
t[0]() call.


Also even though it says just XS in function parameters it has 
this special meaning, basically 'argument list'. (you can do cool 
tricks like this 
https://dlang.org/phobos/std_traits.html#Parameters)


lazy is parameter storage on function argument.

Also I noticed that no explicit generic types were provided in 
your call. I assume this means that D's type system is similar 
to Typescript's then, where it's a logical constraints and will 
try to "fit the holes" so to speak.


In Typescript it works like this:

  function myFunc(arg: T) {}
  myFunc(1) // T is inferred to be type "number"
  myFunc("a") // T is inferred to be type "string"
  myFunc(1) // Same as above, but explicit, maybe 
useful if you want to verify arg, else pointless


It seems like potentially D is similar here?


I'm not that familiar with TypeScript but it looks close enough 
to what C# and C++ does, but yes it is like you described it, 
except explicit types is not to verify but to force it to be of 
that type when compiler is too confused or you need to use some 
specific base class or interface.


Re: Creating a .di file for a custom C library

2021-03-30 Thread evilrat via Digitalmars-d-learn

On Tuesday, 30 March 2021 at 04:01:12 UTC, Brad wrote:
I would like to use an updated version of the Termbox library 
(written in C) with D.  I have the .h file.  This is new 
territory for me (why try something easy - right?).  I think I 
need to create a .di file that corresponds to the .h file.  I 
also suspect that I need to put the library file (C code) into 
the project as a file somehow.  I am probably just not looking 
in the right place for the documentation, but I cannot seem to 
find a lot of guidance in this area.


Thanks in advance.


No just convert C signatures to corresponding D signatures in 
regular .d file.
Then you need to build original C library, and then when building 
D program you link(pass produced .lib/.a files to 
compiler/linker) this stuff with C library.


After all your binaries is just language agnostic bytes, however 
there is calling conventions that exist for interop, your .h 
contains definitions (aka contract) of what it does, and produced 
binaries (.exe, .a, .lib, .dll, .so) contains actual machine 
code, so on D side you must match that contract and then tell the 
linker to embed the machine code from .a/.lib in your final 
executable/DLL.


Re: Why I need DUB? Will never DMD don't just use import for import packages?

2021-04-08 Thread evilrat via Digitalmars-d-learn

On Thursday, 8 April 2021 at 21:36:02 UTC, Alain De Vos wrote:

The most important task is
"give me a list of to include .d files"
"give me a list of the link libraries .a .so"


sure, use -v flag, this will give you compiler flags and other 
info

```
   dub build -v
```
this will give you extensive build information in json
```
   dub describe
```
also if you don't like dub going internet just add this flag
```
   --skip-registry=all
```


Re: How to allow +=, -=, etc operators and keep encapsulation?

2021-04-12 Thread evilrat via Digitalmars-d-learn

On Monday, 12 April 2021 at 18:16:14 UTC, Jack wrote:

Give this class:

```d
class A
{
int X() { return x; }
int X(int v) { return x = v;}

private int x;
}
```

I'd like to allow use ```+=```, ```-=``` operators on ```X()``` 
and keep encapsulation. What's a somehow elegant way to do that?


I assume you know what you are doing, right?
In this specific case I would say you can probably stick with it 
as is since you can have value checks in getter/setter, you can 
validate and correct values before it mess up the internal state, 
and calculate X without exposing internal state (today it may be 
int x, tomorrow you change it to be stored as string, who 
knows...).


But this example doesn't really tell if it's acceptable in what 
you are trying to achieve.


Otherwise:

What you need is called abstraction, you provide high level 
interface to your problem without exposing internal state which 
is implementation detail, which gives you freedom to modify 
internal logic without breaking everyone's code that consume your 
interface.


Assuming A is some special scalar type you just implement all 
operations in a way that makes it only relevant as a whole. 
Otherwise if you still need to peek on its private members you 
have leaky abstractions (it is called feature envy).




  1   2   3   >