Re: Splitting a project into different executable files
On Saturday, 12 October 2024 at 01:09:56 UTC, Alexander Zhirov wrote: Is it possible to organize a project that will consist of several main files. I want to write several simple programs in one project, but for them to be divided into different files. So that it would be possible to choose during compilation what to build, via dub. Is this possible? Not sure if this what you need, but anyway. I using this project structure, have a root dub folder, and then have a subfolders for isolated components of the project. My project is game so in the future it might to have main executable and dedicated server, this should be able to choose what to build with configurations. overall here is the dub config, I have root package to build everything I need at once (using dependencies declaration), and then it should be possible to add second configuration. And as usual, dub can build any subpackage like this `dub build game:somepackage`. *(don't mind that it is a dynamic library, i have external app loading lib but principle will be the same for regular executables with main function)* __dub.json__ ```json { "authors": [ "John Smith" ], "copyright": "Copyright © 2023, John Smith", "description": "some game", "license": "proprietary", "name": "game", "subPackages": [ { "name": "core", "targetType": "dynamicLibrary", "targetPath": "coregame/bin", "sourcePaths": ["coregame/source"], "importPaths": ["coregame/source"], "dependencies": { "gameengine" : "~>0.1.0" } } ], "dependencies": { "game:core": "*" }, "configurations": [ { "name": "default", "targetType": "none" } ] } ``` If later I need to add dedicated server build it would be another entry in "configurations" something like this, where D version will be choosing between two main() functions or just modify control flow if needed. then choosing between targets will be just like this **`dub build`** for regular app **`dub build -c dedicated`** for server build ```json "configurations": [ { "name": "default", "targetType": "none" }, { "name": "dedicated", "targetType": "none", "versions": [ "DedicatedServer" ] }, ] ```
Re: Wrapper for PAM
On Monday, 7 October 2024 at 08:23:08 UTC, Alexander Zhirov wrote: I tried to build a class with a private function `conversation_func` to call it inside the public authentication function. When compiling I get this message: ``` source/login/auth.d(87,46): Deprecation: casting from extern (C) int delegate(int num_msg, const(pam_message**) msg, pam_response** resp, void* appdata_ptr) to extern (C) int function(int, const(pam_message**), pam_response**, void*)* is deprecated ``` And when I start up, at the moment of calling the authentication function, I get `Segmentation fault`. Is the function identified differently in the class? How can this be fixed? Of course it segfaults, you are trying to give delegate pretending it is to be a standalone function. For example you can fix it by using a trampoline - Make a global class instance somewhere, make conversation_func static (if you absolutely want it to be in class) and then in that function use instance.actual_conversation_func, that will do actual work. Maybe other solutions exists that is not variation of this method by I can't come up with anything else.
Re: Associative Array, get value instead of poiter using `if (auto ..)`, possible?
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: How do you typically debug / write D code (Visual Studio - known to be broken in Error pane etc), VScode - I get this error...
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: Being reading a lot about betterC, but still have some questions
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: Pointer to dlang spec for this alias construct?
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: How to use D without the GC ?
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: Unintentional sharing?
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 pass in reference a fixed array in parameter
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: How to pass in reference a fixed array in parameter
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
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: need help to use C++ callback from garnet
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: D doesn't have weak references. So how can I make a associative array of objects without preventing their destruction?
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: D doesn't have weak references. So how can I make a associative array of objects without preventing their destruction?
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: Question on shared memory concurrency
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: Help optimize D solution to phone encoding problem: extremely slow performace.
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: Help optimize D solution to phone encoding problem: extremely slow performace.
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.
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.
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.
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: Less verbose or at least "higher level" 2D game engines for Dlang.
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: [vibe] what's wrong with linking time of vibe applications?
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: [vibe] statically precompile some JS libs into an app binary
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: What is :-) ?
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: What is :-) ?
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 :-) ?
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: Translating C precompiler macros to D
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: Symbolic computations in D
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: Symbolic computations in D
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: Can't get into debugger in vscode on macOS
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: How to get all modules in a package at CT?
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: Meaning of the dot-function syntax
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: change object class
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: pipeProcess output to hash string
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: malloc error when trying to assign the returned pointer to a struct field
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: malloc error when trying to assign the returned pointer to a struct field
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: I don't understand betterC
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: I don't understand betterC
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
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: Using Windbg to debug D applications and unittests
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: Using Windbg to debug D applications and unittests
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
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: How to a link to a C library to create static bindings?
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: Hipreme's #8 Tip of the day - Using custom runtime with dub projects
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: Hipreme's #8 Tip of the day - Using custom runtime with dub projects
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: Function which returns a sorted array without duplicates
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: Non-ugly ways to implement a 'static' class or namespace?
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: Vibe.d serve files from filesystem
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: Background thread, async and GUI (dlangui)
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: What happened to Circular Studio?
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: Trying to cross compile from windows to android
On Thursday, 20 January 2022 at 19:31:06 UTC, H. S. Teoh wrote: I'm not sure how it works on Windows, but there should be corresponding binaries that might give a hint as to what's the correct -fuse-ld=... option you need to use. Here I documented some of the quirks I've hit during android prototyping. Works like this, no idea if it is still up to date though. https://github.com/Superbelko/android-sdl-d/blob/master/guide/README.md
Re: Good intellisense support IDE/Editor?
On Wednesday, 22 December 2021 at 10:37:51 UTC, Michel wrote: Hey, I've tried coding in Visual Studio Code but there isn't any function checking/showing what arguments a function accepts, I can just write `Foo.Bar("somerandomarg");` and it will not give me errors or warnings. Which IDE do you guys use to get proper intellisense? Thanks VS Code(code-d plugin) and VisualD(Visual Studio only) are the best available for D and does show you errors like that if set up and cofigured correctly, but really nowhere near compared to pro tools for C#/Java, additionally most D language plugin/IDE relies on "dcd" or "libdparse", which becoming less and less useful as D evolves. (I don't blame them, but unfortunately their time has passed) Finally there is no tool that can handle complex UFCS chains or templates(like filter, map, etc..).
Re: How to pass a class by (const) reference to C++
On Wednesday, 15 December 2021 at 12:02:08 UTC, Jan wrote: On Wednesday, 15 December 2021 at 11:03:27 UTC, rikki cattermole wrote: On 15/12/2021 11:54 PM, Jan wrote: On Wednesday, 15 December 2021 at 09:36:54 UTC, Jan wrote: Unfortunately it's the "annoying little details" that I immediately bumped into. Just another example: I just learned that linking against C++ DLLs is quite limited. I ran into the issue that linking in an external variable doesn't work (even though the mangled name that D chooses is correct), because DLLs work differently than static linking does Are you sure that on the shared library side it was marked as exported? If a symbol is not exported, there is no guarantee (nor reason to think) that it will be visible during runtime linking to said shared library/executable. This isn't unique to D, its just how linkers work. Yep, checked that. Even checked the .exp file and compared the mangled name there with the mangled name that D tries to use, they are the same. You probably know this but just in case - unlike C++ in D variables by default have thread local storage, to link with C++ global variable you need to use __gshared storage modifier in D, it is similar to 'shared' variable that unlike 'shared' tells the compiler "I know how to synchronize it myself". ```d module a; struct Foo {} extern(C++) __gshared Foo globalFoo; ```
Re: How to pass a class by (const) reference to C++
On Tuesday, 14 December 2021 at 06:21:39 UTC, Tejas wrote: Hey, evilrat, I've seen people make claims that our C++ interop has reached phenomenal levels and that going any further would basically require a C++ compiler ala ImportC++, the issue is just that the docs haven't been updated yet to reflect it. What do you think about this? Is this really true? Because it sure doesn't look that way to me :( Unfortunately it is mostly true. There is some missing features like above tail ref and const, there is minor mangling issues that requires pragma mangle sometimes, and other annoying little details. Aside from that there is things that requires actual C++ compiler OR at least part of it to enable certain C++ features - like the example above with pass-by-value for classes certainly requires real C++ copy constructor, some operator overloads, use of SFINAE instead of CTFE, and I'm sure there is more of such nuances. All this not going to happen, D spec clearly states it allows limited C++ interop by relying on linker mechanics rather than being C++ compatible language. It is now abandoned but there was LDC fork called "Calypso", it was a mixed clang/LDC compiler that aimed to achieve seamless D/C++ interop and from what I've heard it was working just fine without all this hiccups as above.
Re: How to pass a class by (const) reference to C++
On Monday, 13 December 2021 at 12:16:03 UTC, Ola Fosheim Grøstad wrote: On Monday, 13 December 2021 at 12:08:30 UTC, evilrat wrote: Yeah but it sucks to have making C++ wrapper just for this. I think either pragma mangle to hammer it in place or helper dummy struct with class layout that mimics this shim logic is a better solution in such cases. Literally anything but building C++ code twice for a project. Does something like this work? ``` class _A {} struct A {} extern(C++) void CppFunc(ref const(A) arg); void func(_A a){ CppFunc(*cast(A*)a); } ``` Only if this struct matches class memory layout, the only potential problem is ctor on C++ side. Also C++ class will likely be NOT zero initialized and have byte gaps due to alignment, this can mess up many things including (default) equality operators and such. That example is still looks very conspicuous because it is very likely does nothing on the caller side in C++ as it passes a copy. Such things may indicate that the library author have no idea what he is doing, and it works on occasion. All this will require extra care or it will explode in your face, and is quite hard to debug without such low-level knowledge of details.
Re: How to pass a class by (const) reference to C++
On Monday, 13 December 2021 at 11:13:12 UTC, Tejas wrote: On Monday, 13 December 2021 at 09:21:26 UTC, Jan wrote: On Monday, 13 December 2021 at 07:48:34 UTC, evilrat wrote: On Sunday, 12 December 2021 at 21:24:39 UTC, Jan wrote: In D I have an extern(C++) class: ```cpp extern(C++) class A { ~this(); // other stuff } ``` An a function that takes A by const reference: ```cpp void CppFunc(const A& arg); ``` But how do I bind this in D ? ```cpp extern(C++) void CppFunc(A arg); // tries to pass as 'A*' extern(C++) void CppFunc(ref const(A) arg); // tries to pass as 'A const * const &' ``` I have solved similar problems with other classes by declaring them as struct in D, but that only works for classes that have no virtual functions. I now have a class where I do need to use a class on the D side, and now I have problems passing these objects to C++. You can tell compiler to mangle it as struct/class using extern(C++, struct). ```d extern (C++, struct) // will use struct mangling even though it's a class class SomeDClass { ... } ``` I tried this, but it doesn't work, because it seems D decides how to pass the object by whether it is a class or struct in D, not in C++. So even with the change as you suggested it, it still tries to pass the object as a pointer to begin with. You'll have to use something called a [shim](https://en.wikipedia.org/wiki/Shim_(computing)), it seems. For example: `main.d` : ```d extern(C++) class A{} extern(C++) void cppFunc_shim(A arg); void main(){ A a = new A(); cppFunc_shim(a); } ``` `cppShim.cpp` : ```c++ class A{}; extern void cppFunc(A const &arg); void cppFunc_shim(A *param){ const A forwardingVar = A(*param); cppFunc(forwardingVar); } ``` `cppFunc.cpp` : ```c++ #include "iostream" class A{}; void cppFunc(A const &arg){ //std::cout << arg << std::endl; std::cout << "Called cppFunc :D" << std::endl; } ``` Then pass the following on the command line(assuming all files are in the same directory): `ldmd2 main.d cppFunc.o cppShim.o -L-lstdc++` That's what it took to make it work for me, dunno if more convenient methods exist. Hope it helps :D Yeah but it sucks to have making C++ wrapper just for this. I think either pragma mangle to hammer it in place or helper dummy struct with class layout that mimics this shim logic is a better solution in such cases. Literally anything but building C++ code twice for a project.
Re: How to pass a class by (const) reference to C++
On Sunday, 12 December 2021 at 21:24:39 UTC, Jan wrote: In D I have an extern(C++) class: ```cpp extern(C++) class A { ~this(); // other stuff } ``` An a function that takes A by const reference: ```cpp void CppFunc(const A& arg); ``` But how do I bind this in D ? ```cpp extern(C++) void CppFunc(A arg); // tries to pass as 'A*' extern(C++) void CppFunc(ref const(A) arg); // tries to pass as 'A const * const &' ``` I have solved similar problems with other classes by declaring them as struct in D, but that only works for classes that have no virtual functions. I now have a class where I do need to use a class on the D side, and now I have problems passing these objects to C++. You can tell compiler to mangle it as struct/class using extern(C++, struct). ```d extern (C++, struct) // will use struct mangling even though it's a class class SomeDClass { ... } ```
Re: How to "stringnify"?
On Sunday, 10 October 2021 at 08:28:30 UTC, rempas wrote: Is there a way to "stringnify" in Dlang? In C we would do something like the following: `#define STRINGIFY(x) #x` What's the equivalent in D? That's probably depends on what you are trying to achieve. If you want to write code-like string that looks like a code you can use token strings https://dlang.org/spec/lex.html#token_strings ```d string code = q{ float sqr(float x) { return x * x; } }; ``` For other symbols there is .stringof property (beware, it's behavior is not part of the spec) https://dlang.org/spec/property.html#stringof ```d class MyClass() { static this() { registerSmth(MyClass.stringof); // pass "MyClass" string } } ``` And there is stuff for metaprogramming such like this in std.traits https://dlang.org/phobos/std_traits.html#ParameterIdentifierTuple
Re: What is the meaning of @future ?
On Saturday, 18 September 2021 at 08:02:13 UTC, Dylan Graham wrote: On Friday, 17 September 2021 at 14:37:29 UTC, Meta wrote: On Friday, 17 September 2021 at 10:31:34 UTC, bauss wrote: On Thursday, 16 September 2021 at 20:53:34 UTC, Elmar wrote: [...] It's just another "useless" attribute that the language has added before fixing any of the real problems :) Basically it reserves a symbol for the future. It's similar to creating ex. an empty function that throws an error or something like "Not implemented" While I understand why it was added and what purpose it serves then I fail to see why that was prioritized over actual issues. It's solving an almost non-existing issue. I think the main reason it was added is because Sociomantic asked for it, but they are of course not around anymore. Off topic: what happened to them, out of curiosity? IIRC they went out of business for inability to compete OR it was consumed by a another advertising company, there was a thread on a forum from Sonke about that event.
Re: std.stdio.File is throwing with the message of: "Access Violation"
On Saturday, 21 August 2021 at 23:50:51 UTC, Ruby The Roobster wrote: On Saturday, 21 August 2021 at 23:50:08 UTC, Ruby The Roobster wrote: On Saturday, 21 August 2021 at 06:08:17 UTC, evilrat wrote: First parameter for CreateWindow should be window class string that you used in wndclass.lpszClassName = appName.toUTF16z; Fix: wndclass.lpszClassName = "Test"; //May need casting... Anyways, this isn't an issue anymore. I'm just not gonna use Win32 API. Of course this is the "fix", but your example works fine and opens a file when window is created. What I don't really understand is why you are trying to remove import core.sys.windows.windows which contains declarations for HWND, HINSTANCE and family... It simply won't compile without it.
Re: C to D convertor
On Saturday, 21 August 2021 at 08:14:22 UTC, Виталий Фадеев wrote: I know, i know... It not possible, but part of the C code we can to convert to the D. Show me, please, solutions, projects, tools, scripts, docs. Can you give the link ? `htod` is 1. Any more ? dstep https://code.dlang.org/packages/dstep dpp https://code.dlang.org/packages/dpp ohmygentool https://github.com/Superbelko/ohmygentool
Re: std.stdio.File is throwing with the message of: "Access Violation"
On Friday, 20 August 2021 at 21:19:09 UTC, Ruby The Roobster wrote: int myWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int iCmdShow) { // ... if(!RegisterClassA(&wndclass)) { return 0; } hwnd = CreateWindowA( "Test", "Test", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL); ShowWindow(hwnd, iCmdShow); UpdateWindow(hwnd); See the results(what matters is if you get the "Access Violation" error or not, everything else is irrelevant). Fix your code first. Your code is broken and in its current state fails to create window, hwnd = 0. GetLastError reports 1407 - ERROR_CANNOT_FIND_WND_CLASS. First parameter for CreateWindow should be window class string that you used in wndclass.lpszClassName = appName.toUTF16z;
Re: D equivalent of C++ explicit
On Thursday, 19 August 2021 at 18:04:58 UTC, Tejas wrote: On Thursday, 19 August 2021 at 17:43:59 UTC, Paul Backus wrote: On Thursday, 19 August 2021 at 17:38:14 UTC, Tejas wrote: As the topic says: Is there an equivalent to C++'s `explicit` keyword in D? No, because all constructors are explicit in D. Oh... then I guess I'll have to manually insert the explicit casts where C++ is doing implicit casts when calling constructors(God help me D: ) You don't have to, here is a binding generator with code conversion, even if it produces junk you can just copy paste relevant code. https://github.com/Superbelko/ohmygentool
Re: How to call destructor before free without dropping @nogc?
On Thursday, 19 August 2021 at 15:12:03 UTC, Ferhat Kurtulmuş wrote: On Thursday, 19 August 2021 at 07:30:38 UTC, Bienlein wrote: Hello, I allocate some instance of class C manually and then free the memory again: [...] I just wanted to leave this here. https://github.com/AuburnSounds/Dplug/blob/master/core/dplug/core/nogc.d This is cool, but even in unit tests for malloc wrapper there is only simple case with class without references to another class and no dtor. Seems like the issue is that one have to add @nogc constructor/destructor overloads for emplace/destroy, and the author can't have @nogc dtor because of writeln (IIRC @nogc using GC is allowed with `debug` anyway), and all class members of another classes must recursively provide them as well.
Re: How to call destructor before free without dropping @nogc?
On Thursday, 19 August 2021 at 08:25:23 UTC, Bienlein wrote: Oops, I just realized that you can also not call emplace when @nogc is present. Well that is at least consistent with not either being able to call destroy ;-). So, I guess this means that you can forget about manually allocating and freeing some instance of a class and using @nogc as well. That's a pitty, @nogc was a good idea. you are probably doing something wrong, could you try @nogc ctor? anyway @nogc is way too limiting, I don't see why bother when there is already `scope` storage (should work in nogc) and -vgc flag to show possible allocations. ```d import core.lifetime; import core.stdc.stdio; import core.stdc.stdlib; class SomeClass { int a = 42; this() @nogc { } this(int val) @nogc { a = val; } } @nogc void main() { byte[64] mem; mem.emplace!SomeClass(); printf("stack %d\n", (cast(SomeClass) mem.ptr).a); // 42 scope a = new SomeClass(); printf("scope %d\n", a.a); //42 SomeClass dynAlloc = cast(SomeClass) malloc(__traits(classInstanceSize, SomeClass)); dynAlloc = emplace!SomeClass(dynAlloc, 123); printf("dynamic %d\n", dynAlloc.a); // 123 } ```
Re: Two major problems with dub
On Wednesday, 4 August 2021 at 07:21:56 UTC, Denis Feklushkin wrote: On Sunday, 1 August 2021 at 17:37:01 UTC, evilrat wrote: vibe-d - probably because it handles DB connection and/or keep things async way, sure you probably can do it with Phobos but it will be much more PITA and less performant It is because Postgres provides JSON types Than again like I said it is library author mistake, if only JSON is ever used then it should depend on vibe-d:data specifically and not the whole vibe-d thing.
Re: Two major problems with dub
On Sunday, 1 August 2021 at 17:25:26 UTC, Alain De Vos wrote: A simple example, dub package dpq2 pulls in, money,vide-d,stdx-allocator,derelict-pq,derelict-util This all for a handfull of C-functions. let's see Money - fits pretty ok, cause your average SQL has decimal type for that purpose but there is no built-in one in D vibe-d - probably because it handles DB connection and/or keep things async way, sure you probably can do it with Phobos but it will be much more PITA and less performant stdx-allocator - memory management, and it is also possible to reduce GC pauses it is probably uses malloc'ed buffers derelict-pg - C API wrapper for PostgreSQL derelict-util - handles function pointers loading for that wrapper That's it. Why do you think this is bloat? You know, D coders are very careful when it comes to using dependencies, it's not like in JS where shit got imported just because it exists, so I don't get your complains on that.
Re: Two major problems with dub
On Sunday, 1 August 2021 at 15:38:32 UTC, Alain De Vos wrote: 2. Let's say you need bindings to postgresql library and you will see dub pulling in numerous of libraries, which have nothing at all to do with postgresql. More like a framework stuff. This creates unneeded complexity, bloatware, dependency hell, maintainability, in my humble opinion. Dub should do one thing and do it good. Feel free to elaborate. Wait, you don't use isOdd package in your frontend? No way... (also for that "bloat" part, this is where the linker comes in and strips it all, unless you are talking about accidentally added dependencies on "just in case" basis which is a sign of design issues)
Re: How to create friends of a class at compile time?
On Thursday, 15 July 2021 at 17:49:06 UTC, Tejas wrote: I'm sorry, I should've explicitly mentioned I'm interested in learning how to do friend injection in D. I know that access specifiers operate at module scope, seen a few posts about that here already. Thank you for answering though. Probably the only way is CRTP (unlikely) or mixin that access internals. Both will be limited and cumbersome to use though. Additionally there is "package" visibility kind that takes optional package name to give access to specific package. https://dlang.org/spec/grammar.html#attributes (under visibility attributes) I rarely use package visibility so might be incorrect, but here an example anyway. ```d module somepackage.somemod; struct A { private int x; // only accessible from same module package int y; // accessible from any module in 'somepackage' package(otherpackage) int z; // accessible from 'otherpackage' package } ```
Re: Why can't we transpile C++ to D?
On Thursday, 10 June 2021 at 19:06:42 UTC, Tejas wrote: But how scalable will this be? We have to get real D code to enrich our ambiguously-defined-small ecosystem. It says bindings generator, but it has to convert the code keeping the semantic as close as possible. It does direct translation on AST level (AST-to-source currently), there is quirks here and there, semantic discrepancies(for example sizeof/alignof differs in D vs C++), lack of struct inheritance and multiple inheritance, and other annoying stuff like implicit casts or implicit constructors, but overall this should work. Definitely better than doing it all by hand. I tried to run it on clang, phew, got 241k lines, and that's without .cpp files. Haven't even bothered with fixing it to compilable state (even then it will definitely have linking issues).
Re: Why can't we transpile C++ to D?
On Thursday, 10 June 2021 at 15:09:02 UTC, Tejas wrote: Sorry, I'm rather ignorant when it comes to this, but why can't we use [pegged](https://github.com/PhilippeSigaud/Pegged) to transpile C++ code to D? Then we won't need a nogc compatible std library and so many other things could get easier, like getting legacy code to use Dlang. It might not be worth it for C+17 and beyond, but older codebases could benefit significantly, right? I leave this here, it does converts C++ to D to some extent https://github.com/Superbelko/ohmygentool
Re: Why can't we transpile C++ to D?
On Thursday, 10 June 2021 at 15:57:44 UTC, Imperatorn wrote: On Thursday, 10 June 2021 at 15:09:02 UTC, Tejas wrote: Sorry, I'm rather ignorant when it comes to this, but why can't we use [pegged](https://github.com/PhilippeSigaud/Pegged) to transpile C++ code to D? Then we won't need a nogc compatible std library and so many other things could get easier, like getting legacy code to use Dlang. It might not be worth it for C+17 and beyond, but older codebases could benefit significantly, right? I'm guessing it's hard because of the grammar Well, still a grammar, though it was my little WTF moment. for example this C++ grammar(often used in STL) where min is simple minimum function ```cpp float min(float l, float r) { return (l < r) ? l : r; } ``` ```cpp float foo(float a, float b) { return (min)(a,b); } ``` and this direct translation to D doesn't works ```d float foo(float a, float b) { return (min)(a,b); // Error: C style cast illegal, use `cast(min)(a , b)` } ``` but this does ```d float foo(float a, float b) { return (&min)(a,b); // ok } ```
Re: Class member initialization with new points to a single instance?
On Wednesday, 9 June 2021 at 17:56:24 UTC, Gregor Mückl wrote: Consider the following code: ```d class Foo { } class Bar { Foo foo = new Foo(); } void main() { Bar b1 = new Bar(); Bar b2 = new Bar(); assert(b1.foo != b2.foo); } ``` The assert fails. This is completely surprising to me. Is this actually expected? By design. What you see is CTFE instance shared through class member initializer. Use Bar ctor instead if you want them to be unique. Yep, confusing for the first time.
Re: Any 3D Game or Engine with examples/demos which just work (compile&run) out of the box on linux ?
On Monday, 7 June 2021 at 14:02:14 UTC, Prokop Hapala wrote: Basically I'm desperate do find anything which encapsulates OpenGL calls into some nice D-lang classes to learn from it. I don't really want to use Dagon, nor Godot. What I want is to use it as learning resources fro learning graphics programming in Dlang. Rewriting my graphics engine from C++ to Dlang is huge barrier for me, sice I don't know Dlang enough. I want to see some nice Tricks and convenience of Dlang features applied to graphics programming. Ability to compile without much hessel is minimal requirement for me. The only thing which I was able to compile up to no was dmech, which is nice for physics but very old OpenGL Ok then, no dagon won't help you that much IMHO. There is definitely a lot of projects on github with some basic engine-like functionality which encapsulates VBO, shaders, and stuff. Nothing specific that comes to mind but they do exist.(uh, maybe serpent engine?) They are however mostly quickly hacked up student's homework rather than designed solid projects, so I again suggest you to try godot for anything serious. It's all shaders after all, doing VBO and render pipeline setups is not that much fun. For learning graphics programming however D is ok, but you will definitely almost on your own, still github is your friend, look for existing projects on github (for example dash) on how it can be done. As for actual language features that might help - that will be reflection and meta-programming. With them you can generate everything from the code - VBO's, render passes, etc... Make declarative DSL from that to rule them all! It's fancy and all, but it is only slightly better than C++ (esp. since it has shitty OpenGL/vulkan loaders and clumsy build tools) and there's nothing new compared to it. And final option would be to make bindings for your existing C++ code, either manually or with tools (like my own generator) https://github.com/Superbelko/ohmygentool
Re: wanting to try a GUI toolkit: needing some advice on which one to choose
On Wednesday, 2 June 2021 at 05:43:49 UTC, evilrat wrote: Yep, use Skia/Cairo or something like this, don't build your own full blown 2D engine for every possible graphics API. I would like to tune my C++ bindings generator to be able to handle Skia ASAP, but can't tell when it will be possible. It happens that Skia now has C API. I've generated C bindings and made my own BindBC package from it. https://github.com/Superbelko/bindbc-skia
Re: wanting to try a GUI toolkit: needing some advice on which one to choose
Btw there is also (dear) imgui, which is immediate mode GUI that builds geometry to draw for you, how one would draw it is up to programmer. It is very popular in game dev because there is very little setup to get it working. Source https://github.com/ocornut/imgui D bindings with GL3 demo https://github.com/Superbelko/imgui-d On Tuesday, 1 June 2021 at 23:50:35 UTC, Ola Fosheim Grøstad wrote: Not sure how that relates to Skia? Skia is used in many products. If I was to use D for something serious, Skia would probably be the first thing I would consider... Yep, use Skia/Cairo or something like this, don't build your own full blown 2D engine for every possible graphics API. I would like to tune my C++ bindings generator to be able to handle Skia ASAP, but can't tell when it will be possible.
Re: Any 3D Game or Engine with examples/demos which just work (compile&run) out of the box on linux ?
On Tuesday, 1 June 2021 at 20:07:39 UTC, Prokop Hapala wrote: After some sime I tried to return to this, using dependency on older version of dagon I got errors in dlib Not sure how to understadn this ``` Error: incompatible types for (box.pmax) - (box.center): both operands are of type Vector!(float, 3) ``` If both operands are the same time `Vector!(float, 3)` I would think the subtractioon is defined in dlib ... why not ? Error messages sucks sometimes. It is likely related to const/ref combinations, for example vector operator- overloads accepting const refs and you have regular mutable vectors. D ref's is somewhat messy. Anyway I tried dagon in past and I don't see why bother with it, better stick with something that can handle industry standard formats such as FBX, another issue is shaders fused in right in the engine. As an alternative the only thing probably worth checking is godot-d which is native interface for scripting in Godot Engine. This engine has its quirks though (my most hated "feature" is that it requires you to create script config for each your native class).
Re: wanting to try a GUI toolkit: needing some advice on which one to choose
On Tuesday, 1 June 2021 at 06:31:28 UTC, Ola Fosheim Grostad wrote: On Tuesday, 1 June 2021 at 05:27:41 UTC, Imperatorn wrote: On Tuesday, 1 June 2021 at 03:32:50 UTC, someone wrote: [...] Yeah, "fragmentation" is a problem. We do a lot of things 90%. We need more "100% projects" that are just plug n play rather than plug n pray The solution is to reduce the scope of projects, but that requires design and planning. Hobby projects tend to be experiments that evolve over time. Would like to pay for something that's not exists where there is already like 10 "good enough"(tm) alternatives? How much people actually use D and willing to pay for that? That's the chicken-egg problem - no funding because no decent solutions, no decent solutions because such enormous effort requires compensation. Another issue is that these hobby projects are not state of the art solutions, they stuck in early 90's (ok, maybe late 90's), where the rest of the world using different architectures and approaches that was evolved several times from then. And yet people who asks for UI libraries goes like "nah, no fancy schmancy CSS, and no markup. gimme good ol' programmatical approach" or "bloat bloat bloat, no thanks"
Re: wanting to try a GUI toolkit: needing some advice on which one to choose
On Sunday, 30 May 2021 at 07:03:38 UTC, Chris Piker wrote: On Thursday, 27 May 2021 at 07:00:32 UTC, Imperatorn wrote: I would like to recommend DlangUI [1], but we have tried now for months to get in contact with the owner of it (to take over development) and are getting no reponse. 1. https://github.com/buggins/dlangui Of the 107 forks of dlangui last seen on github, do you know if any contain more recent changes/features than the buggins original repo? If there's a quick way to check without paging through all of them I'm curious to know how it would be done. I'm using D for efficient server-side processes only, since at work we're heavily invested in Java for our end-user GUIs, but I'm curious about the state of D GUI toolkits nonetheless. "Insights -> Network" will show branching overview where you can clearly observe what changes were made on each fork https://github.com/buggins/dlangui/network DlangUI is somewhat primitive but I like it that way, one can quickly hack up pretty much any widget (including graphics) without too much hassle, just subclass suitable widget for the base, override few methods and start hacking. Of course I would like it to be real MVVM with view/data separation, visual/logical hierarchy separation, data bindings, UI automation and stuff. Maybe I'll fork it one day to make it that way, but at this moment I already have too much stuff to do.
Re: How does inheritance and vtables work wrt. C++ and interop with D? Fns w/ Multiple-inheritance args impossible to bind to?
On Tuesday, 25 May 2021 at 18:12:27 UTC, Gavin Ray wrote: On Tuesday, 25 May 2021 at 18:03:00 UTC, evilrat wrote: That last one with someInt is what I warned about. D ctor messed up class layout, in this simple case where class data isn't used it almost works, but will be practically unusable in real scenarios. Ah =/ You have this in your code example: ```d static assert(Derived.someInt.offsetof == 16); // that's important otherwise D ctor will mess up everything ``` Would this fix it, or is it just not super viable to hack around C++ multiple inheritance in D? Maybe generating some wrapper C++ code to be linked could help too? I'm not sure though/don't really know enough to say Both this features uses mixins, but does conceptually different things, my example with manual vtable casts is simpler but more mechanical, and it basically mimics how it actually works. Anyway the problem is with D side, compiler emits incorrect type info/layouts (no wonder, it is clearly stated multiple inheritance not supported), and then everything explodes. So one of the possible workarounds is to separate class layout and API with mixins/templates. No idea how it will affect usability though, it's quite possible that extending such horrible construct from D side would be cumbersome, too much PITA to do real job using that thing. Hard to say for sure without experiments. Also like I said, D already does half of the work, it just needs to collect all base classes and arrange vtable. One of the potential blockers could be frontend architecture, I don't know how much stuff such change would break, I think pretty much everything was designed with single base class in mind. Like this one, it has 'this' pointer, ctor/dtor and fields, but no mention about layouts anywhere. https://github.com/dlang/dmd/blob/master/src/dmd/aggregate.d#L86 The closest what it could be is https://github.com/dlang/dmd/blob/master/src/dmd/aggregate.d#L279
Re: How does inheritance and vtables work wrt. C++ and interop with D? Fns w/ Multiple-inheritance args impossible to bind to?
On Tuesday, 25 May 2021 at 17:52:14 UTC, Gavin Ray wrote: ```d void main() { Derived dlangDerived = new Derived(123); printf("[D] Derived.Base1::getSomething() = %d \n", dlangDerived.getSomething()); printf("[D] Derived.Base2::getOtherThing() = %d \n", dlangDerived.getOtherThing()); printf("[D] Derived.Base1::inheritedFunctionWithArgs(5, 10) = %d \n", dlangDerived.inheritedFunctionWithArgs(5, 10)); printf("[D] Calling C++ takesADerived() with D Derived* \n"); takesADerived(dlangDerived); } ``` ![output](https://i.imgur.com/Plbtlow.png) That last one with someInt is what I warned about. D ctor messed up class layout, in this simple case where class data isn't used it almost works, but will be practically unusable in real scenarios.
Re: How does inheritance and vtables work wrt. C++ and interop with D? Fns w/ Multiple-inheritance args impossible to bind to?
On Tuesday, 25 May 2021 at 08:10:25 UTC, sighoya wrote: On Tuesday, 25 May 2021 at 02:47:19 UTC, Gavin Ray wrote: The below seems to work at least, which is encouraging: Awesome! At least, it becomes problematic with fields in base classes, it would be nice if we could map them to @property annotated functions in D interfaces. I did some basic testing with code above, it seems class layout is recursively linear at least on Windows, and D follows C++ rules close enough, at least it works if one comments out all but the first base, and the rest can be hand crafted using structs and templates. With this code it is possible to pass back C++ class received from C++ code and call it. So it seems support for multiple inheritance shouldn't be that hard to implement (for Windows), no idea how it works on Linux though. ```d // replacement for second base template iBase2() { // final is needed or it will call overrideMe1 instead of this final void overrideMe2() { static struct _layout { void* b1; void* b2; int someInt; } _layout* base = cast(_layout*) cast(void*) this; alias fn = extern(C++) void function(void*); fn _fn = *cast(fn*) base.b2; // vtable for Base2, vtable[0] is overrideMe2 _fn(cast(void*)this); } } class Derived : Base1 //, Base2 { mixin iBase2 __base2; alias overrideMe2 = __base2.overrideMe2; static assert(Derived.someInt.offsetof == 16); // that's important otherwise D ctor will mess up everything } ``` Maybe I'll be able to create templated base class that does all this stuff with mixins and templates. like this ```d extern(C++) abstract class MultipleInheritance(T...) { // implementation // } class Derived : MultipleInheritance!(Base1, Base2) { ... } ```
Re: How does inheritance and vtables work wrt. C++ and interop with D? Fns w/ Multiple-inheritance args impossible to bind to?
On Tuesday, 25 May 2021 at 02:47:19 UTC, Gavin Ray wrote: Unfortunately, it does not work if I try to add `final int getSomething()` or the other one to the D interfaces, it throws a symbol error because the mangled names are slightly different: ```sh unresolved external symbol "public: int __cdecl Base1::getSomething(void)" (?getSomething@Base1@@QEAAHXZ) T ?getSomething@Base1@@QEAA?BHXZ # < "nm" output ``` If I use `nm` and list the symbols, and then try to manually use the mangling scheme, it almost works but because the return types differ it won't compile =/ ```d extern class Derived : Base1, Base2 { int someInt; pragma(mangle, "?getOtherThing@Base2@@QEAA?BHXZ") int getOtherThing(); } ``` ```sh main.d(29): Error: Function type does not match previously declared function with the same mangled name: `?getOtherThing@Base2@@QEAA?BHXZ` main.d(29):Previous IR type: i32 (%main.Base2*) main.d(29):New IR type: i32 (%main.Derived*) ``` That's just LDC thing, should work with DMD. Are you sure `getOtherThing` marked final? Because in your C++ class it is not virtual and in your example it is not final as well. In C++ having multiple bases with final method means that both Base1 and Base2 have their own instances of that method. Anyway in order to call it you'll have to cast manually to target base. i.e. if you want to call `Base1::getOtherThing` and you have `Derived` you'll have to cast to `Base1`. ```d Derived d; // d.getOtherThing(); // likely won't link (cast(Base1)d) .getOtherThing(); // will call Base1 variant (cast(Base2)d) .getOtherThing(); // will call Base2 variant ``` It is also possible that you'll have to put them in using mixin template so it will create scope for them that doesn't collide with each other, though I think it's more of a hack than a feature. Something like ```d class Derived { mixin base1; // has final getOtherThing mixin base2; // has final getOtherThing } ``` then you can call it almost like in C++ ```d d.base1.getOtherThing(); d.base2.getOtherThing(); ``` Anyway all this stuff requires thorough research & testing as such ABI tinkering is very easy to mess up and very hard to debug, for example if you mess up the order(functions layout) it can land on another final method call that seemingly work but in debugger you'll see that you can't hit breakpoint in that method. Happy debugging time!
Re: gtkd ,drawingarea, capture mouse pressed
On Friday, 21 May 2021 at 12:28:36 UTC, Alain De Vos wrote: On a gtkd drawingarea I want to capture the mouse-pressed event and get the coordinates of the pointer on the area. I have ``` addEvents(GdkEventMask.BUTTON_PRESS_MASK); ``` Maybe I must add a signal-handler ? Not a gtk user, but maybe this will help (has quite a list of examples on gtkd, newest first) https://gtkdcoding.com/
Re: What is the difference between these template declaration forms?
On Saturday, 15 May 2021 at 08:37:21 UTC, cc wrote: Are these identical? Or is there a different usage for the (T : something) form? ```d auto opCast(T)() if (is(T == bool)) { return _obj !is null; } ``` They are the same in this case. ```d auto opCast(T : bool)() { return _obj !is null; } ``` While the docs says it matches the most specialized type, which is bool in this case, IIRC it is actually takes anything convertible to bool despite what the docs says. You should double check it yourself. Anyway I would usually pick this form where possible as it yields cleaner error messages unlike arbitrary template constraint "stuff X doesnt takes Y, did you mean (basically X but not)" message that who knows what it wants you to do.
Re: Cannot access frame pointer of a struct with member function
On Sunday, 9 May 2021 at 17:37:40 UTC, Andrey Zherikov wrote: Compilation of this code: ```d auto foo(T)() { return T(); // Error: cannot access frame pointer of `onlineapp.main.T` } void main() { struct T { int a=1; void argsFunc(int a) {} // (1) } pragma(msg,foo!T()); } ``` fails with this error: ``` onlineapp.d(3): Error: cannot access frame pointer of `onlineapp.main.T` onlineapp.d(14): Error: template instance `onlineapp.foo!(T)` error instantiating onlineapp.d(14):while evaluating `pragma(msg, foo!(T)())` ``` But when I comment out argsFunc function on line (1), it compiles successfully meaning that there is no issue to access frame pointer. Is this a bug? Most likely because function member types have access to the scope, it complains because doing so will escape the scope of that function. If you make struct static this erorr should go away.
Re: SDL2 Android vulkan question
On Sunday, 2 May 2021 at 16:06:10 UTC, Danny Arends wrote: On Sunday, 2 May 2021 at 12:35:51 UTC, evilrat wrote: As for SDL2, are you sure it was built with Vulkan support? That's the thing I worry about, since the SDL2 libraries are locally build using android studio and I'm kind of a noob in that. Ok, since this is potentially the case, just to clarify, building C/C++ with CMake for Android these days is basically one extra parameter pointing to CMake toolchain file in your local NDK location when configuring your build. https://developer.android.com/ndk/guides/cmake#file (from the docs) ``` $ cmake \ -DCMAKE_TOOLCHAIN_FILE=$NDK/build/cmake/android.toolchain.cmake \ -DANDROID_ABI=$ABI \ -DANDROID_NATIVE_API_LEVEL=$MINSDKVERSION \ $OTHER_ARGS ``` Then I would probably use gradle for the rest of the process to produce apk, including copy libraries step.
Re: SDL2 Android vulkan question
On Sunday, 2 May 2021 at 12:35:51 UTC, evilrat wrote: On Sunday, 2 May 2021 at 08:58:30 UTC, Danny Arends wrote: Any thoughts on why loading the Vulkan library using SDL2 would not work ? thoughts in general about the process ? Just few tips. GC "crashes" since you have custom main, D default main has runtime initialization code so it "just works", in you custom main function try to do this before any call to D code. Oops, nevermind. I thought you've missed runtime initialization at all but you have rt_init. In that case you can try disable parallel collection, or it could be a bug. https://dlang.org/spec/garbage.html#gc_config https://dlang.org/spec/garbage.html#gc_parallel As for SDL2, are you sure it was built with Vulkan support? Do you have any other Vulkan apps to test if it actually supported by your device? SDL2 docs also says vulkan load library should be called only after you created window surface. It is hard to say from provided code if you have that too. Anyway, I might try to look at this next weekend. Do you have this project available on github/google drive?
Re: SDL2 Android vulkan question
On Sunday, 2 May 2021 at 08:58:30 UTC, Danny Arends wrote: Any thoughts on why loading the Vulkan library using SDL2 would not work ? thoughts in general about the process ? Just few tips. GC "crashes" since you have custom main, D default main has runtime initialization code so it "just works", in you custom main function try to do this before any call to D code. https://dlang.org/phobos/core_runtime.html#.Runtime.initialize ```d extern(C) main() { import core.runtime; Runtime.initialize(); scope(exit) Runtime.terminate(); } ``` As for SDL2, are you sure it was built with Vulkan support? Do you have any other Vulkan apps to test if it actually supported by your device?
Re: Deriving a D-class from a CPP-class
On Wednesday, 28 April 2021 at 19:46:00 UTC, Alain De Vos wrote: It is rather clear what I want to achieve but virtual functions give me headache because dlang does not now the word virtual. It's virtual by default. The opposite is `final`.
Re: How to skip class/function when using -HC flag to generate C++ headers?
On Monday, 19 April 2021 at 17:37:31 UTC, MoonlightSentinel wrote: On Monday, 19 April 2021 at 16:26:20 UTC, evilrat wrote: Or maybe there is a way to tell it whitelist/blacklist modules? The header generator only translates modules passed on the command line, other declarations are omitted unless they are required by another symbol. Omit the modules from your blacklist when generating the header file (allthough that requires rerunning dmd) Ok thanks, well, time for new dub subconfig. Or... maybe at least pre-build step for that specific module.
How to skip class/function when using -HC flag to generate C++ headers?
It is annoying, it tries to write all derived classes where it only needs interface. Or maybe there is a way to tell it whitelist/blacklist modules? Marking class private is not an option.
Re: How to allow +=, -=, etc operators and keep encapsulation?
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).
Re: Why I need DUB? Will never DMD don't just use import for import packages?
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: Creating a .di file for a custom C library
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: How to declare "type of function, passed as an argument, which should have it's type inferred"? (or if D had an "any" type)
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: How to declare "type of function, passed as an argument, which should have it's type inferred"? (or if D had an "any" type)
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: WinUI 3
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: Is there an easy way to convert a C header to a D module?
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: Workaround to "import" an exception from a DLL
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".