Re: Question on shared memory concurrency

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

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

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


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


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


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


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


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

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

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


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



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


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


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


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


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

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

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


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


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


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

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

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

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


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


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

```



Perhaps using this option when running Java will help:

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


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


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

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

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


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

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

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

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

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

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


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


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




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


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


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


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

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

On Wednesday, 17 January 2024 at 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.

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

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

Hello everyone,

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


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


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


Thank you for your time.


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


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





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

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

D lang noted as having a very fast compilation time.

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


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




Welcome to template bloat hell.

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


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




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

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


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


Sure, try enum with import expression.

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

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

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

That enum will have that asset embedded in your executable.

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


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


Re: What is :-) ?

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

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


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


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


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


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


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


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


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

```


Re: What is :-) ?

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

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


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


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




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


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


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



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

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

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




Re: What is :-) ?

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

On Monday, 20 November 2023 at 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 
`` 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

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


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

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


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



```d
import std.stdio;

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

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

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

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

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

return _res;
}

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

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


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

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


Re: Symbolic computations in D

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

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


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


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

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

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


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

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

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


Re: Symbolic computations in D

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

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

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


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


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


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

IIRC Vibe.d using them for template engine.

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

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

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


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

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

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


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


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


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


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


Could it be is that it instantly crashes?

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


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


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


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




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

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

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


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


Is there document about this ModuleInfo?

I only find Struct object.ModuleInfo

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

Which seems different.


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


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


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


Re: Meaning of the dot-function syntax

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

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

Hi,

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

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

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


Thanks,
dhs


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


Re: change object class

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

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


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


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


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


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


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

That is up to you of course.



Re: pipeProcess output to hash string

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

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


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


Windows maybe? Try this.

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






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

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

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


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




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


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


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


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

alias u64 = ulong;
alias i64 = long;

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

  u64 _len = 0;

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

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

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

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

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

extern(C)
void main()
//unittest
{
enum el = 3;
auto vec = Vec!char(10);
assert(vec._ptr);
vec[el] = 'h';
assert(vec[el] == 'h');
printf("ptr = %p\n", vec._ptr);
printf("vec ptr = %p\n", [el]);
printf("vec local = %p\n", );
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

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

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

I do have the following struct:

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


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

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

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

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

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


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


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


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


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


I assume you already tried debugging your program, right?

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


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


Re: I don't understand betterC

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

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


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


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


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


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


Re: I don't understand betterC

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

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


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


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


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


Re: I don't understand betterC

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

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


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

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

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


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




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


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

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

void main() { }

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

```



Re: Using Windbg to debug D applications and unittests

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


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


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


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


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


Re: Using Windbg to debug D applications and unittests

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


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


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

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





Re: Using Windbg to debug D applications and unittests

2023-02-25 Thread evilrat via Digitalmars-d-learn
On Saturday, 25 February 2023 at 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?

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


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




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


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




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

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

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


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


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


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


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

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

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


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


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


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


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


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

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


Re: Function which returns a sorted array without duplicates

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

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



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


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


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

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

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

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






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

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

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


Ok, thanks.

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


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


```d
module modulename;
```

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


```d
import modulename;
```

to the file that uses it.


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


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

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

```d
static import std.stdio;

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

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


Re: Vibe.d serve files from filesystem

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

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

Hello everyone,

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


Thanks in advance.

eXo


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


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


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

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



```d
// PSEUDOCODE

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

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

```



Re: Background thread, async and GUI (dlangui)

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

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


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


...

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


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


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


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



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


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


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

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

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

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

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

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


Re: What happened to Circular Studio?

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

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


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


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


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


-Steve


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


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


Re: Trying to cross compile from windows to android

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

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?

2021-12-22 Thread evilrat via Digitalmars-d-learn

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++

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

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++

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

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++

2021-12-13 Thread evilrat via Digitalmars-d-learn
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++

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

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 );

void cppFunc_shim(A *param){
const A forwardingVar = A(*param);
cppFunc(forwardingVar);
}

```

`cppFunc.cpp` :

```c++

#include "iostream"
class A{};

void cppFunc(A const ){
//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++

2021-12-12 Thread evilrat via Digitalmars-d-learn

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"?

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

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 ?

2021-09-18 Thread evilrat via Digitalmars-d-learn
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"

2021-08-21 Thread evilrat via Digitalmars-d-learn
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

2021-08-21 Thread evilrat via Digitalmars-d-learn

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"

2021-08-21 Thread evilrat via Digitalmars-d-learn
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())
{

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

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

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?

2021-08-19 Thread evilrat via Digitalmars-d-learn
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?

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

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

2021-08-04 Thread evilrat via Digitalmars-d-learn
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

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

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

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

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?

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

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?

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

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?

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

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?

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

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 ()(a,b); // ok
}
```


Re: Class member initialization with new points to a single instance?

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

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) out of the box on linux ?

2021-06-07 Thread evilrat via Digitalmars-d-learn

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

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

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

2021-06-01 Thread evilrat via Digitalmars-d-learn
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) out of the box on linux ?

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

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

2021-06-01 Thread evilrat via Digitalmars-d-learn
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

2021-05-30 Thread evilrat via Digitalmars-d-learn

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?

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

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?

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

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?

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

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?

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

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

2021-05-21 Thread evilrat via Digitalmars-d-learn

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?

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

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

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

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

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

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

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

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

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

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

2021-04-29 Thread evilrat via Digitalmars-d-learn

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?

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

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?

2021-04-19 Thread evilrat via Digitalmars-d-learn
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?

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

On Monday, 12 April 2021 at 18:16:14 UTC, Jack wrote:

Give this class:

```d
class A
{
int X() { return x; }
int X(int v) { return x = v;}

private int x;
}
```

I'd like to allow use ```+=```, ```-=``` operators on ```X()``` 
and keep encapsulation. What's a somehow elegant way to do that?


I assume you know what you are doing, right?
In this specific case I would say you can probably stick with it 
as is since you can have value checks in getter/setter, you can 
validate and correct values before it mess up the internal state, 
and calculate X without exposing internal state (today it may be 
int x, tomorrow you change it to be stored as string, who 
knows...).


But this example doesn't really tell if it's acceptable in what 
you are trying to achieve.


Otherwise:

What you need is called abstraction, you provide high level 
interface to your problem without exposing internal state which 
is implementation detail, which gives you freedom to modify 
internal logic without breaking everyone's code that consume your 
interface.


Assuming A is some special scalar type you just implement all 
operations in a way that makes it only relevant as a whole. 
Otherwise if you still need to peek on its private members you 
have leaky abstractions (it is called feature envy).




Re: Why I need DUB? Will never DMD don't just use import for import packages?

2021-04-08 Thread evilrat via Digitalmars-d-learn

On Thursday, 8 April 2021 at 21:36:02 UTC, Alain De Vos wrote:

The most important task is
"give me a list of to include .d files"
"give me a list of the link libraries .a .so"


sure, use -v flag, this will give you compiler flags and other 
info

```
   dub build -v
```
this will give you extensive build information in json
```
   dub describe
```
also if you don't like dub going internet just add this flag
```
   --skip-registry=all
```


Re: Creating a .di file for a custom C library

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

On Tuesday, 30 March 2021 at 04:01:12 UTC, Brad wrote:
I would like to use an updated version of the Termbox library 
(written in C) with D.  I have the .h file.  This is new 
territory for me (why try something easy - right?).  I think I 
need to create a .di file that corresponds to the .h file.  I 
also suspect that I need to put the library file (C code) into 
the project as a file somehow.  I am probably just not looking 
in the right place for the documentation, but I cannot seem to 
find a lot of guidance in this area.


Thanks in advance.


No just convert C signatures to corresponding D signatures in 
regular .d file.
Then you need to build original C library, and then when building 
D program you link(pass produced .lib/.a files to 
compiler/linker) this stuff with C library.


After all your binaries is just language agnostic bytes, however 
there is calling conventions that exist for interop, your .h 
contains definitions (aka contract) of what it does, and produced 
binaries (.exe, .a, .lib, .dll, .so) contains actual machine 
code, so on D side you must match that contract and then tell the 
linker to embed the machine code from .a/.lib in your final 
executable/DLL.


Re: How to declare "type of function, passed as an argument, which should have it's type inferred"? (or if D had an "any" type)

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

On Monday, 29 March 2021 at 17:52:13 UTC, Gavin Ray wrote:

Trying to read this function signature:

void my_func(T, XS)(string a, string b, string c, lazy T 
function(XS)[] t...)


Does this say "Generic void function 'my_func', which takes two 
generic/type params "T" and "XS", and is a function of type 
"string a, string b, string c", and..." (this is where it 
starts to get hazy for me):


How does one interpret/read this:

   lazy T function(XS)[] t...


A tuple of functions that takes XS argument(s) and returns T.

'...' part is a tuple/variadic arguments, however with function 
it is somewhat wacky and requires an array notation [], otherwise 
compiler treats it like a mere pointer for some reason, same with 
t[0]() call.


Also even though it says just XS in function parameters it has 
this special meaning, basically 'argument list'. (you can do cool 
tricks like this 
https://dlang.org/phobos/std_traits.html#Parameters)


lazy is parameter storage on function argument.

Also I noticed that no explicit generic types were provided in 
your call. I assume this means that D's type system is similar 
to Typescript's then, where it's a logical constraints and will 
try to "fit the holes" so to speak.


In Typescript it works like this:

  function myFunc(arg: T) {}
  myFunc(1) // T is inferred to be type "number"
  myFunc("a") // T is inferred to be type "string"
  myFunc(1) // Same as above, but explicit, maybe 
useful if you want to verify arg, else pointless


It seems like potentially D is similar here?


I'm not that familiar with TypeScript but it looks close enough 
to what C# and C++ does, but yes it is like you described it, 
except explicit types is not to verify but to force it to be of 
that type when compiler is too confused or you need to use some 
specific base class or interface.


Re: How to declare "type of function, passed as an argument, which should have it's type inferred"? (or if D had an "any" type)

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

On Monday, 29 March 2021 at 15:13:04 UTC, Gavin Ray wrote:
Brief question, is it possible to write this so that the "alias 
fn" here appears as the final argument?


  auto my_func(alias fn)(string name, string description, auto 
otherthing)


The above seems to work, since the type of "fn" can vary and it 
gets called inside of "my_func", but from an ergonomics point 
I'd love to be able to put the function last and write it 
inline:


  my_func("name", "description", "otherthing", (x, y, z) {
auto foo = 1;
return foo + 2;
  })


Currently I am calling it like:

  auto some_func = (x, y, z) {
auto foo = 1;
return foo + 2;
  };

  my_func!some_func("name", "description", "otherthing");

Which is fine, it's just that from a readability perspective it 
doesn't really allow for writing the function inline and you 
need to declare it separately.


Not a huge deal, just learning and thought I would ask =)

Thank you!


Also with delegates (lazy), you get the type checks however you 
must have to declare parameters on call site, which can be PITA 
in the future when doing refactoring will be necessary.


Better plan ahead as the number of changes will explode when you 
make quite a number of these and decide to change params/returns.


```
  import std.stdio;

  void my_func(T, XS)(string a, string b, string c, lazy T 
function(XS)[] t...)

  {
// call function, just the first one, can call all of them as 
well

t[0](a);

// can get the result too, mind the future refactoring needs 
tho

// T res = t[0]();
  }

  void main()
  {
my_func("name", "description", "otherthing", (string x) {
  writeln(x);
  return x;
});

// no function, compile error
// my_func("name", "description", "otherthing");
  }
```


Re: WinUI 3

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

On Monday, 15 March 2021 at 16:41:08 UTC, Imperatorn wrote:

Could D be used with WinUI 3?

https://docs.microsoft.com/en-us/windows/apps/winui/winui3/

Would the win32metadata help? 樂


I've seen some slides about WinUI 3 future directions and roadmap 
but haven't tried it yet.
Probably it will be PITA to use it right now in anything not .NET 
because of some core dependencies (IIRC some core stuff is in 
.NET), but plans have mentions it will be possible to use with 
ANY language closer to release date somewhere in Q3 2021.


But if it can be done using C++/WinRT right now then it is highly 
likely this will be possible to do it in D as well.


As for WinRT stuff there was some tools and bindings done by 
webfreak.

https://github.com/WebFreak001/dwinrt2
and/or
https://github.com/WebFreak001/dwinrt


Re: Is there an easy way to convert a C header to a D module?

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

On Monday, 15 March 2021 at 02:43:01 UTC, Tim wrote:

On Monday, 15 March 2021 at 02:03:09 UTC, Adam D. Ruppe wrote:

On Monday, 15 March 2021 at 01:53:31 UTC, Tim wrote:
I'm needing to use a c/c++ library in a D program and I'm 
struggling with creating a binding as it seems like an 
enormous amount of regex modifications. Is there an existing 
program that can create most if not all of a binding for me?


https://github.com/jacob-carlborg/dstep

That does most of it, then you fix it up with some regex or 
whatever to finish the job.


Seems pretty good. Does it work on c++ stuff too?


(shameless plug) You can try my crappy generator[1] for C++

There is also dpp[2] which probably can convert C++ decls to D

[1] https://github.com/Superbelko/ohmygentool
[2] https://code.dlang.org/packages/dpp


Re: Workaround to "import" an exception from a DLL

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

On Sunday, 14 March 2021 at 09:35:40 UTC, frame wrote:


// this returns null in the program (but works in a debugger 
watch):

MyExceptionObj imported = cast(MyExceptionObj)e;

// this actually works:
MyExceptionObj imported = cast(MyExceptionObj) cast(void*)e;





Is there are way to copy the exception data in a new Throwable 
instance that can be thrown from the current context? Or can 
the runtime be tricked by overwriting the TypeInfo in memory? 
(I don't know exactly what the actual problem is.)


As a workaround maybe you could introduce special 
DLLWrapperException with reference to original exception using 
cast hack?


The problem is that TypeInfo is not shared on Windows, which is 
actually roots deeper in the other problems with "sharing".
Unfortunately I cannot provide you with details, but this 
situation is well known long standing issue.


From what I understand it is such a mess because D 
compiler/linker doesn't merge multiple symbols in running program 
which is how it basically works in C++ where DLL's works "as 
expected".


Re: Can't I allocate at descontructor?

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

On Friday, 5 March 2021 at 05:31:38 UTC, Jack wrote:
The following code returns a memory error. I did notice it did 
happens whenever I did a memory allocation. Is this not 
possible in the descontrutor? if so, why?




GC prohibits allocation during collection, since this dtor is 
likely called by GC this is what happens.


If you REALLY need this just allocate using other mechanisms.


Re: Shared library module system with dub

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

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

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

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


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


Try this (for dub.json)

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

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


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


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



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


In most cases this is undesireable, so instead one will usually 
put all common stuff into DLL and share across main executable 
and other DLL's that relies on it.


On Windows however DLL support is unfinished, so you are stuck 
with hacks and/or static libs option.




Re: How can I make this work?

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

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


for example, I need something like this to work:

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


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


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




Re: DUB is not working correctly

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

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

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

"targetType": "executable",

and it should just run using "dub run"


Unfortunately, the problem remains :/


Looks like something specific to your machine.

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


Re: DUB is not working correctly

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

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


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


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


Re: DUB is not working correctly

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

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


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

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




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


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



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



Re: DUB is not working correctly

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

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


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


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


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


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


Doesn't seem like an installation problem.

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


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


Re: is it posible to compile individual module separately?

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

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

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


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


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


   "dflags": [ "-lowmem" ],

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


   dub build --compiler=dmd


Re: Is there other way to do that?

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

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




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


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



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


```
import std;

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

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

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

```




Re: Can change vtbl record at runtime ?

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

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

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


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


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


Re: Class Allocators

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

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


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

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


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


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



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

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

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

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

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

Here is the source code:

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


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

*/


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






Re: Dll crash in simplest case

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

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

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

[...]


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

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

__gshared HINSTANCE g_hInst;

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

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

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

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

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

default:
}
return true;
}
---


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


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

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

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


Qt5 dlls


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

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


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




  1   2   3   >