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().




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

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

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

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

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


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


All dependencies inside an exe file. Like Python Pyinstaller.


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


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

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

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

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


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

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

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

is this possible? if so, how?


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


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


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


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

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

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


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



 is this documented somewhere? Is this going to change?


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


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


Re: How to debug D on Linux

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

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


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


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


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


Re: Collections in D

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

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


What about sets?


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


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

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


Re: How build DCD on Windows?

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

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


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

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


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




Re: Developing and running D GUI app on Android

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

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

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


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


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


Re: Developing and running D GUI app on Android

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

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


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


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


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

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


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


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


Re: C++ or D?

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

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


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


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


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


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


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


Re: Getting started with graphqld

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

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


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



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


Re: Iterating chars by Word

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

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

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


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


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

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

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

}

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

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

import std.array : split;

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

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


Re: Getting Qte5 to work

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

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


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




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


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


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

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


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

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




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


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


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



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


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

$> dub init MyAwesomeProject

  - Now go to this folder
$> cd MyAwesomeProject

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

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

$> dub add qte5

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

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

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


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


  - Build using dub
$> dub build

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


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

$> dub generate visuald

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





Re: How to compile Windows exe files from this source

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

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

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

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


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


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







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

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

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

I changed string to basic_string.

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

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

static Canvas Create();

basic_string!ubyte Foo();

basic_string!ubyte Bar();
};
}

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

writeln(canvas.Foo());

writeln(canvas.Bar());
}

Error ...

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


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


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


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




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

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

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


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


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


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

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


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

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

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


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

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


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


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


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


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

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

Pseudocode:

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

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

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

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

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

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





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

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

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


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

classes from D?


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


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


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


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

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

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


To apply this I have this following struct:

module bst;

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

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

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

}
}

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

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

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

}


When I run the unittest the compiler complains:

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


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

Why does this happen?


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


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


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




Re: Linker error under Ubuntu

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

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


Dub should do the linking by itself.


How does it know what to link?



Re: Linker error under Ubuntu

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

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


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

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

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


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


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


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


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

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

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


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


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


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


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

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

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


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

How would it be?


Replying myself...

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


can be simplified as:

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


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

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

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


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

Does anybody have any clues what is going on ?


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

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


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


Re: A question about C++ interop

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

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


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


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

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


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


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


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


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


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


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




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


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


Re: dub libs from home directory on windows

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

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

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


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


Thank you very much for your help.


I see, you want without hardcoded path...


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


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


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


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


example batch:

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



Re: AA code 50x slower

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

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


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


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


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


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


Re: AA code 50x slower

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

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

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



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

This is especially bad with loops.

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

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


Re: How the hell to split multiple delims?

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

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


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

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



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


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


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





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

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




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

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




Re: How to check that import module will succeed?

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

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


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

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

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


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


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


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

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

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

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


Re: How to check that import module will succeed?

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

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


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


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

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


Re: Wrong vtable for COM interfaces that don't inherit IUnknown

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

On Monday, 15 July 2019 at 22:01:25 UTC, KytoDragon wrote:
I am currently trying to write a XAudio2 backend and have come 
across the problem, that some of the interfaces for XAudio2's 
COM objects seem to be missing the first entry in their vtable. 
After reading the iterface article in the spec 
(https://dlang.org/spec/interface.html#com-interfaces) it seems 
that only interfaces inheriting from 
core.stdc.windows.com.IUnknown (or any interface named 
"IUnknown") get the COM interface layout instead of the D 
layout.


What can I do to get the COM layout on interfaces that don't 
inherit IUnknown?
Examples: IXAudio2Voice or any of the IXAudio2*Callback 
interfaces. I have already declared everything extern(Windows), 
but that does not fix it.


As you can see it is by design. IUnknown has different vtbl[] 
comparing to regular D classes/interfaces. If it works with 
declaring your own empty IUnknown use it, also you can try 
extern(C++) which does similar thing to vtable, it might even 
work!


Another option is to craft your own "vtable" with structs, but 
I'm not going into details about that, you can always google how 
to do it in C and adapt.


And finally you can swap vtable for object instances at runtime, 
this however is the most complicated and error prone solution, I 
for example doesn't fully understand D rules for vtable 
constructing, esp. confusing is that interface entry notice, so 
anything non trivial (such as class inheriting from class 
w/multiple interfaces) is beyond me. Expect heavy AV storm.



Also from what I see MS done this intentionally, means they 
either no longer loves COM or there was some other good reason.



Oh and let me put this here...
Have you seen this? It even has very simple xaudio example.
https://code.dlang.org/packages/directx-d


Re: Heterogeneous Variadic Arguments with Other Arguments

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

On Sunday, 14 July 2019 at 03:51:14 UTC, harakim wrote:

I wanted to do this:
package int serialize(byte[] destination, int offset, T...)(T 
values)




Can't really tell what's going on without call site and what do 
you exactly mean by "heterogeneous arguments with other 
arguments", but this thing is syntax error. You declared a 
template here, and template parameters (compile-time parameters) 
must come first.


   int serialize(T...)(byte[] destination, int offset, T values)

This is the case if you wanted to pass that buffer at runtime, 
not sure if you can do this with CT parameters, though it 
shouldn't prevent you from forcing CTFE evaluation by assigning 
result to another CT parameter or enum.



But if by "other arguments" you mean passing different types 
there is untyped variadics with a bit different behavior(see [1])



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





Re: question about call cpp class constructer without new , and define cpp delegate

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

On Thursday, 27 June 2019 at 17:00:01 UTC, Rémy Mouëza wrote:


I though support for C++ allocation had improved. In a recent 
release, there was the addition of core.stdcpp.new, but I 
didn't try it out:

- http://dpldocs.info/experimental-docs/core.stdcpp.new_.html
- https://en.cppreference.com/w/cpp/memory/new/operator_new


It seems at this moment these operators only supported on Windows.


Are there still pitfalls to be wary of?


Not possible:

- new/delete (not entirely impossible, but requires to dig in 
compiler/library internals, generally fragile and not portable, 
not even mention that deciphering STL code is just meh...), 
though many libraries provides their own allocator/deallocator 
functions and some even provides pluggable hooks to use.

- Member functions pointers
- Multiple inheritance (tbh this is considered a bad practice 
anyway and chances to encounter it relatively small)

- lambdas?
- Exceptions? (except maybe on Windows, because of SEH)
- Template instantiations code gen(this basically requires to 
implement entire C++ compiler), what this means is that if the 
concrete template instance isn't used in a library you use you 
have to make dummy C++ function that forces compiler to emit the 
code for it.



Possible, but annoying:

- Functions with ref parameters

- Functions with const pointers to mutable data parameters
  ex: float calcStuff(float * const arr, size_t len);
It doesn't make sense in D, and I doubt there is much sense in 
C++ as well (except maybe to convey the meaning that this 
function won't try to free data).
So the workaround of course is to slap pragma mangle, which of 
course requires manually getting the mangled name for the 
function...


On Windows using MS compiler for the example above the mangled 
name will look like

  float calc(float * const arr); // ?calc@@YAMQEAM@Z
and for non const
  float calc(float * arr); // ?calc@@YAMPEAM@Z

so it is possible to do something like this
  pragma(mangle, calc.mangleof.replace("QEA","PEA"))
  float calc(float * arr);

- Some operator overloads also needs pragma mangle treatment.

- Incomplete/buggy mangling support, especially annoying with 
templates. Same treatment.



Maybe I've missed something else though, but anything not on the 
list usually works without surprises. And thanks to string 
namespaces it is now such a relief to use.


Re: question about call cpp class constructer without new , and define cpp delegate

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

On Thursday, 27 June 2019 at 05:37:08 UTC, ChangLoong wrote:
If I want call cpp class constructer without new method, is 
there a way to do that ?


If what you really want is to actually allocate using C++ new 
operator from D, then that is very problematic and not portable 
even across compilers on same OS.


If C++ side has poor design around this specific issue and 
expects passed object to be delete'd (using the C++ delete 
operator) later then you are in trouble. In that case you have to 
make simple wrapper on C++ side to be able to call new/delete 
from D.


If all you want is to allocate memory for object(existing buffer, 
malloc, etc..) and place it there you can use emplace function 
and call ctor later (see below)
https://dlang.org/phobos/core_lifetime.html#.emplace , or there 
was one in "object" module IIRC


Otherwise it is also possible to just call constructors manually 
using its internal name

   myObj.__ctor(..params..) / this.__ctor(...)

(destructors also possible, see __dtor/__xdtor. hint: __dtor is 
probably not what you want, read the docs first)


And finally to just allocate with GC using D new operator
   auto myObj = new MyClass(...);

Just make sure that this object won't be delete'd from C++


and also if the cpp api accept a delegate as parameter, how to 
create one from d and pass to cpp ?


Probably not possible. There are no delegates in C++, instead it 
has pointers to member functions and limited lambdas, and there 
is no analogs in D. You can try to craft it somehow to be ABI 
compatible, but probably easier to just make simple wrapper on 
C++ side.
IIRC member pointers is just pointer, and you provide 'this' 
context on call, while in D delegate is 2 pointers - context AND 
function


Re: How can I override the defeat compiler select by Dub?

2019-06-23 Thread evilrat via Digitalmars-d-learn

On Sunday, 23 June 2019 at 23:10:48 UTC, Mike Brockus wrote:
If you never seen Meson before then pick up a camera and take a 
picture:

樂  https://mesonbuild.com/



Nope. Wasn't working on Windows last time I checked.

Hometown Meson user here simply just wondering how can I tell 
Dub to use dmd to compile my dependence in Meson?


Isn't there anything in meson recipe to tell dub use 
--compiler=ldc2 switch? Or you can also try moving LDC/GDC in 
your %PATH% so that they come before DMD (works on Windows).


Re: Using python in D

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

On Sunday, 9 June 2019 at 03:42:23 UTC, rnd wrote:


Thanks for guidance.

I also wanted to know: Once executable is successfully created, 
will it work on systems where Python and pandas are not 
installed?


That is unlikely. PyD is just a D package, it doesn't have the 
ability to mess up with your project files to pack proper 
shippable app.


On linux it also adds complexity due the way how dynamic 
libraries are handled (i.e. need to set this fancy RPATH, 
LD_LIBRARY_PATH, whatever else necessary), so I would first make 
isolated python copy using venv(and install required packages) 
and then copy it to your final redistributable dir, might also 
require messing a bit with linker flags (to tell where to look 
for shared libs), but anyway it all depends on what prebuilt 
python depends, for example it will likely fail if run on older 
distro or just distro with older libc, or if any of its other 
dependencies being older or missing.



As for py_import issue you can also try do import within py_stmt 
and see if it works(assuming python has all relevant paths set 
up).


Re: 1 - 17 ms, 553 ╬╝s, and 1 hnsec

2019-05-18 Thread evilrat via Digitalmars-d-learn

On Thursday, 16 May 2019 at 15:19:03 UTC, Alex wrote:

1 - 17 ms, 553 ╬╝s, and 1 hnsec

fancy useless asci hieroglyphic



Holy shirt!
All that time I was thinking this is just some sort of encoding 
artifacts in terminal(common problem on windows), especially 
because IIRC on Linux it is displaying this greek 'micro' 
correctly.


This is completely out of context, and so should be replaced with 
something more conventional...


Now when I realize it, for me it immediately start look like some 
sort of cave art or graffiti in art gallery, very unprofessional 
I say.




Re: is there a way to embed python 3.7 code in D program?

2019-05-13 Thread evilrat via Digitalmars-d-learn

On Monday, 13 May 2019 at 21:29:18 UTC, Danny Arends wrote:


"ImportError: No module named 'stuff'"

How do I make the py_import file from pyd find the stuff.py 
file ?




On Linux PYTHONPATH doesn't have current directory by default, so 
a hacky way to do it is to add it to PYTHONPATH prior to each run


PYTHONPATH=. ./prog

More realistic solution of course is to add it before importing 
anything in your code


void main()
{
py_stmts("import sys; sys.path += './'");
...
}

Or alternatively set the environment variable from D



ps. I removed the vs debugger stuff since I'm on Linux



It is cross platform, I just tested it myself and it works fine. 
You can mixed debugging D and Python is VS Code even on Linux.


Re: C Style char**

2019-05-13 Thread evilrat via Digitalmars-d-learn

On Monday, 13 May 2019 at 09:24:34 UTC, Doug Clayton wrote:

Hi All,

First time poster :)

I'm working on getting a binding to Vulkan working properly in 
D, but I've run into a roadblock. The good news is that the 
binding seems to work fine, but I'm having an issue getting a 
parameter that needs an input of a const(char*)* to receive all 
of the members of the array. It only will receive the first 
member.


I've looked through the documentation, but I haven't seen a 
clear way to cast a char*[] to a char** without it losing the 
rest of the members. Can anyone help?


You don't need to cast it, arrays have .ptr property to get 
pointer to first element, and in @safe you just [0] instead, 
or so I think.


If you are using static/literal arrays and know what you are 
doing this will work.


Otherwise it safer to just use regular string[] array and use 
something like that



const(char*)* toCStringList(string[] arr)
{
import std.string; // toStringz() - adds null terminator, 
allocates using GC if necessary
import std.array; // array() - eagerly converts range to 
array, allocates using GC

import std.algorithm; // map() - apply function to range
return arr
.map!(toStringz)
.array();
}


Re: is there a way to embed python 3.7 code in D program?

2019-05-13 Thread evilrat via Digitalmars-d-learn

On Monday, 13 May 2019 at 03:06:07 UTC, evilrat wrote:


https://github.com/Superbelko/pyd-min

Here. Super minimal example, ptvsd can be commented out as 
well, it is there entirely for debugging.




Pardon me, somehow I was completely misread the original 
question...

Well, maybe someone else will find this useful...


Re: is there a way to embed python 3.7 code in D program?

2019-05-12 Thread evilrat via Digitalmars-d-learn

On Monday, 13 May 2019 at 01:35:58 UTC, evilrat wrote:


I have project using pyd with python 3.7, that also using ptvsd 
(visual studio debugger for python package) to allow mixed 
debugging right inside VS Code.


I'll reduce the code and upload somewhere later.



https://github.com/Superbelko/pyd-min

Here. Super minimal example, ptvsd can be commented out as well, 
it is there entirely for debugging.


Re: is there a way to embed python 3.7 code in D program?

2019-05-12 Thread evilrat via Digitalmars-d-learn

On Sunday, 12 May 2019 at 22:36:43 UTC, torea wrote:


ok, I'll do some more tests with pyd then.
And if I cannot get it to work, I'll have a look at the package!



I have project using pyd with python 3.7, that also using ptvsd 
(visual studio debugger for python package) to allow mixed 
debugging right inside VS Code.


I'll reduce the code and upload somewhere later.




Re: OT - Git training Lon/HK and book recommendation on taste in programming

2019-05-01 Thread evilrat via Digitalmars-d-learn

On Wednesday, 1 May 2019 at 09:51:01 UTC, Laeeth Isharc wrote:


Second question.  Lots of people these days start to program to 
solve their problems at work but they may never have been shown 
the basic principles of design, structuring and maintenance of 
their code.  If I could give them one book (and a few YouTube 
links) what should it be ?




If I understand correctly you basically need something for those 
who already doing some basic scripting but doesn't get any real 
programming skills yet.


In that case "Code Complete" by Steve McConnel probably will be 
the best one for starters, it covers broad range of programming 
aspects.
And my personal recommendations for that one probably to read the 
last (or previous?) chapter first before starting from beginning, 
this is where the whole book is described in 10-20 pages or so, 
this should give the reader short overview of what to expect, 
because reading a lot of stuff will get you anxious to know if 
this is going to be explained later or not, and the book isn't 
short.


But even despite such simplicity, learning programming from zero 
will never be easy.


Re: DLL creation fails with undefined symbol error

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

On Friday, 26 April 2019 at 14:20:24 UTC, dokutoku wrote:


Error: linking with LLD failed
C:\ldc\bin\ldc2.exe failed with exit code 1.



Ok, I have Visual Studio and SDKs installed so it works for me 
without touching anything else.
In your case it is using lld linker instead, and I have no idea 
what libs it requires.


Re: DLL creation fails with undefined symbol error

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

On Friday, 26 April 2019 at 05:08:32 UTC, dokutoku wrote:

I tried to build a DLL in a Windows 64bit environment.
It works well if the compiler is DMD, but in the case of LDC, 
the build fails with a large number of undefined symbol errors.


Is this a DUB or LDC bug?
Or do I have to specify some additional arguments to the 
command?


Seems like DMD links some system and/or runtime libs for you, 
while LDC doesn't.


What symbols are missing? It could be just msvcrt and some of the 
default system libs such as system32 and the like.


Re: Recommendations for best JSON lib?

2019-04-20 Thread evilrat via Digitalmars-d-learn
On Saturday, 20 April 2019 at 20:44:22 UTC, Guillaume Piolat 
wrote:
On Saturday, 20 April 2019 at 18:49:07 UTC, Nick Sabalausky 
(Abscissa) wrote:
I only need to read arbitrary JSON data, no need for 
writing/(de)serialization.


std.json is simple as pie.



However IIRC it fails with trailing commas, means that for 
reading user written JSON's it might be annoying.


I also tried experimental std json, asdf and vibe.d.
The only one that worked for me is vibe.d JSON subpackage, and 
adding simple commented lines stripping is simple with phobos, 
because there is absolutely no libraries that can handle JSON 
comments yet. (yes, I know it's not standard)


Re: DlangUI print too small on retina screens

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

On Saturday, 13 April 2019 at 12:00:30 UTC, Joel wrote:


Thanks for the reply, but I looked it up, and couldn't work out 
what I can do. I want to try using the overrideScreenDPI trick.


option 1 - using override DPI function:
---

// your average hello world UIAppMain()

import dlangui;

mixin APP_ENTRY_POINT;

const SCALE_FACTOR = 2.0f;

/// entry point for dlangui based application
extern (C) int UIAppMain(string[] args) {

// just in case, but dlangui package seems to import 
pretty much everything

import dlangui.core.types;

// pretty much self explanatory, where 96 DPI is "normal" 
100% zoom
// alternatively you can set it to your screen real DPI 
or PPI or whatever it is called now
// however for 4k with 144 DPI IIRC I set it to 1.25 
scale because 1.5 was too big and/or didn't match WPF/native 
elements

overrideScreenDPI = 96f * SCALE_FACTOR;

// now create your widgets and run main loop
...

}


option 2 - temporal override in cached package code (dub only)
---

once you build your app go to dub temporary package cache,
on windows it is %USERPROFILE%\AppData\Local\dub\packages
on linux it is something like ~/dub/packages

go to corresponding dlangui version folder and edit the file
dlangui-###\dlangui\src\dlangui\core\types.d
find PRIVATE_SCREEN_DPI and set it to something bigger that 
closer match your DPI or 96 multiplied by relative scaling

save & rebuild your project


option 3 - clone and edit (dub or manual builds if you know what 
to do)

---

clone dlangui repo somewhere
do steps from option 2 for PRIVATE_SCREEN_DPI
(dub only) in your dub project change dlangui dependency to 
point to where you cloned it

"dependencies": {
"dlangui":  { "version" : "*", "path": 
"your_modifief_dlangui_somewhere" }

},

rebuild, done


Re: DlangUI print too small on retina screens

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

On Friday, 12 April 2019 at 08:39:52 UTC, Joel wrote:
I got a new computer (another MacBook Pro, but this one has 
retina display), now I don't think I can use my main programs 
(done in DlangUI), without eye strain and having my head close 
to the screen.


I noticed a lot of forked versions of the said library. Do any 
have a fix for the tiny print, if so, which one is good?


Thanks in advance.


It should detect DPI for you, and internally do the scaling. 
Though I don't know if it works at all.


In case it is not yet implemented try this 
function[1](overrideScreenDPI from dlangui.core.types) before 
creating your widgets in UI main function, at the very last 
resort you can just change the values in that file as well and 
rebuild (that's what I did for my crappy projects and it was 
working on Windows).


[1]https://github.com/buggins/dlangui/blob/d942853bcd458f563ee3c855332ab58c1f1e5faa/src/dlangui/core/types.d#L317


Re: use dll's

2019-03-16 Thread evilrat via Digitalmars-d-learn

On Saturday, 16 March 2019 at 15:13:15 UTC, ontrail wrote:

On Saturday, 16 March 2019 at 14:18:07 UTC, Andre Pany wrote:

On Saturday, 16 March 2019 at 12:53:49 UTC, ontrail wrote:

hi,
i created a program (windows) and 2 dll's.
how do i use the 2 d-language dll's in a d-language program 
with only one GC?


any help is appreciated.


It is explained here (section d code calling d code in dll)

https://wiki.dlang.org/Win32_DLLs_in_D

Kind regards
Andre


well thank you kindly.
what i don't understand yet, is there a way to have the GC in 
my program only once instead of several times with the dll's.


gc_setProxy is the way, read that article's section again.


Re: DUB / compiling same source and config to different windows subsystems in 32/64 bit

2019-03-05 Thread evilrat via Digitalmars-d-learn

On Tuesday, 5 March 2019 at 05:03:42 UTC, Mike Parker wrote:


This has nothing to do with dub, so that’s the wrong place for 
it. The dmd for windows docs needs to make clear the 
distinction between the linkers and the differences in 
behavior, and point to the linked docs for options. I just 
checked the Optlink page and didn’t see /subsystem documented, 
so that needs to be fixed. I’ll put it on my todo list.


That's right, it is not part of the dub itself, however it is 
directly related to it(both compiler and writing that dub 
platform/config specific project parts), and that adds value on 
usability. Such info is invaluable addition, just put it in the 
extra section like "How-to's" or another similar cookbook 
recipe-like one.


This will help users that are new to Windows(esp. advanced super 
duper *nix power users) to solve their problem instantly where 
this simple, easy to follow steps with a bit of explanation is 
placed in a proper place.


Not to mention that there is definitely more such topics that are 
frequently asked but people forced to dig through forums and 
projects on github to gather that knowledge piece by piece.




Re: DUB / compiling same source and config to different windows subsystems in 32/64 bit

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

On Tuesday, 5 March 2019 at 03:48:22 UTC, Mike Parker wrote:
I stopped using WinMain with D a long time ago. It's not 
necessary. If you always use `main`, then both linkers will 
provide you with a console subsystem app by default. That's 
particularly useful during development. You can add a 
configuration to your dub.json that turns on the windows 
subsystem for both linkers.


For OPTLINK (x86) you only need to pass to the linker 
`/SUBSYSTEM:windows`.


For the MS linker (x86_mscoff, x86_64) you need to that and you 
need to specify that the entry point is `main`, because it will 
expect `WinMain` when you specify the windows subsystem. You 
can do that with `/ENTRY:mainCRTStartup`


https://docs.microsoft.com/en-us/cpp/build/reference/subsystem-specify-subsystem?view=vs-2017
https://docs.microsoft.com/en-us/cpp/build/reference/entry-entry-point-symbol?view=vs-2017


All of this should be added on dub docs with small snippets and 
explanation as a section dedicated to Windows and maybe even on D 
docs as well, because you know, it shows up again and again from 
time to time.


Re: DUB / compiling same source and config to different windows subsystems in 32/64 bit

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

On Monday, 4 March 2019 at 18:34:09 UTC, Robert M. Münch wrote:
Hi, when compiling a minimal Windows GUI app (using WinMain()) 
and compiling it with DUB, the 32-bit x86 version is a 
character subsystem EXE (writeln works) and for x86_64 it's a 
GUI subsystem EXE (writeln doesn't work). Since compiling the 
same source, with the same DUB config file, I would expect the 
x86 and x86_64 version to be equal.


That's the DUB JSON I use:

{
"targetType" : "executable",

"libs-windows-x86_64": ["user32", "gdi32"],
"libs-windows-x86"   : ["gdi32"],
}

So, how can I get a character subsystem for x86_64 and a GUI 
subsystem for x86?


For MS linker just pass the linker flag /SUBSYSTEM:CONSOLE for 
console, or /SUBSYSTEM:WINDOWS for no console, it also detects 
that by the presence of WinMain(), more about linker[1]


This should do for MS linker

"lflags-windows-x86_64": ["/SUBSYSTEM:CONSOLE"],
"lflags-windows-x86_mscoff": ["/SUBSYSTEM:WINDOWS"]

For old optlink x86 it is a bit harder, you need to include 
special .def file that has instruction for linker, here is an 
example from dlangui[2], adding it with linker libs should work, 
probably, or maybe, or...


Ok while I writting this I checked dlangui example[3], so do this 
with that def file


"sourceFiles-windows-x86": ["$PACKAGE_DIR/src/win_app.def"],

[1] 
https://docs.microsoft.com/en-us/cpp/build/reference/subsystem-specify-subsystem?view=vs-2017

[2] https://github.com/buggins/dlangui/blob/master/src/win_app.def
[3] 
https://github.com/buggins/dlangui/blob/master/examples/example1/dub.json#L14


Re: how to pass a malloc'd C string over to be managed by the GC

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

On Thursday, 28 February 2019 at 04:26:47 UTC, Sam Johnson wrote:


Update: it seems that all I need to do is GC.addRoot(output); 
and memory leak goes away. I think I have answered my own 
question.



If you know what you are doing. Otherwise you just postpone 
troubles due to mixed allocator/deallocator which will result in 
memory corruption or just crash. I mean you definitely need to 
remove that root and free() when you're done with it at some 
point later.


Also fromStringz() may internally do implicit GC copy, inspect 
its source, if it just appends to an array or something similar, 
this will likely to implicitly allocate using GC.


If you just want to copy string then arrays has a useful 
.dup()/.idup() methods(properties?)[1] that should give you a GC 
managed copy of original, if I'm not missing something...



If I understood problem correctly then the safest in this case 
will add scope(exit)[1] to free() array.


   char *output = cast(char *) malloc(output_length);
   scope(exit) free(output);  // will go away when leave scope, 
both normal/exception ways


another option will be making RAII struct wrapper that free() on 
destruction, possibly also using RefCounted[2]


To know where GC allocations are made there is -vgc flag for DMD, 
it was added to help writting GC-less code if that's absolutely 
needed, but you can use it to know if you are not messing up 
malloc-free with GC alloc/free.



And finally, don't take what I say too seriously, I do D on 
ocassion these days so there might be some changes in how things 
works or I might just forgot how it really works.



[1] https://dlang.org/spec/arrays.html#array-properties
[2] https://dlang.org/spec/statement.html#scope-guard-statement
[3] https://dlang.org/phobos/std_typecons.html#RefCounted


Re: Setup help?

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

On Wednesday, 6 February 2019 at 23:59:07 UTC, Charles wrote:


I don't use C++, and I do use Windows, which has me wondering 
if I'm just missing some normal/exepcted configuration.


My most recent attempt I tried to get Native Debug to make VS 
Code debugging stop on the first line. Instead, it just runs 
the program, and exits.




"Native Debug" is for GDB and looks like it doesn't even works on 
Windows. But even on Linux I found that C++ tools are much nicer.


You need C++ tools from Microsoft to debug D code, don't mind the 
name, its debugger works for any (compatible formats) native code.


Then add C++ Windows debug configuration and set your paths. 
Done. You can debug now. (Though it is possible that it will 
require Visual Studio Build Tools installation)


Of course this will not work for default DMD builds because it is 
using ancient object files format that is not compatible with VS 
debugger engine, so using DMD you need to build with -m32mscoff 
(dub --arch=x86_mscoff) or -m64 (dub --arch=x86_64) flags.


Re: C++ base class needs at least one virtual method

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

On Wednesday, 6 February 2019 at 07:38:04 UTC, ezneh wrote:


Thanks for the trick, I'll try  it and see how it goes.
Since the class have nothing in them, I just made some "alias 
otherclass = baseclass" statements and it seems it is working 
(at least it's compiling, have to really test that too). From 
what I saw about the code is that those types are just 
"placeholders" because they aren't used directly by the API.




It still might be necessary to add empty struct with 'extern(C++, 
class)' because alias is, well, just alias, and it needs a real 
type because C++ signatures do contains parameters types, and 
obviously there will be no methods that accepts derived class so 
it will fail to link.
That's what that 'alias this' is for. And since this is not 
direct inheritance it will most likely won't work when object 
expected to be passed by value (at least not without casting to 
void* then to base*, i.e. 
'someFunc(*cast(baseclass*)cast(void*))')


Re: C++ base class needs at least one virtual method

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

On Tuesday, 5 February 2019 at 14:23:00 UTC, ezneh wrote:

Hello

While trying to make a 1:1 binding to a C/C++ lib, I got the 
following issue:


I only have access to the .h header file, and in there I have 
this:


class someclass {};
class otherclass : public someclass {};

When trying to translate that header file to D, I ended with 
the following code:


extern(C++):
class someclass {}
class otherclass : someclass {}

But when compiling, the following error comes up:

Error: class `modulename.otherclass` C++ base class someclass 
needs at least one virtual function



Am I missing something or is there a bug somewhere ?
I don't have access to the .cpp file and cannot see what are 
the methods of someclass / otherclass are.


Any suggestion ?


No surprises here, D can only inherit from virtual C++ classes 
and that message says exactly that(class must have at least one 
virtual method).


This someclass looks for me as just a strange design decision, if 
it's not just a POD data object (i.e. simple struct that is 
declared as a class) then normally the class will have at least 
virtual destructor to allow proper destruction.


In case it is really just the POD class you can declare it as 
struct, add it as a member and 'alias this'[1] it to provide 
sort-of-inheritance chain (i.e. it will be implicitly accepted 
using that alias part)


extern(C++)
struct someclass {}

extern(C++)
class otherclass {
someclass baseclass; // <- "inherited" data must go 
before other members to preserve data layout

alias baseclass this; // <- pseudo inheritance alias
...
}

Though in some cases depending on semantic it is possible that it 
might not work as expected. (Though I can't remeber any)


If however otherclass is just a POD as well then you should turn 
it into a struct as well, same for all descendants...


Just in case, there is few tools for generating bindings 
available - dstep(AFAIK no C++)[2], dpp[3], gentool[4], and more 
info on the wiki[5].



[1] https://dlang.org/spec/class.html#alias-this
[2] https://github.com/jacob-carlborg/dstep
[3] https://github.com/atilaneves/dpp
[4] https://github.com/Superbelko/ohmygentool
[5] https://wiki.dlang.org/Bindings




Re: Is there a nice syntax to achieve optional named parameters?

2019-01-18 Thread evilrat via Digitalmars-d-learn

On Friday, 18 January 2019 at 09:39:31 UTC, John Burton wrote:

On Thursday, 17 January 2019 at 01:43:42 UTC, SrMordred wrote:


struct Config
{
string title;
int width;
}

struct Window
{
this(Config config)


It likely is a bad idea for a small struct like this but if it 
was much bigger would it makes sense to write this as :-


this(const ref Config config)

Which is what you might do in C++ or does D handle this 
differently?


You'd better profile and only then act.
Seriously, whatever you know and familiar with in C++ might not 
work with D, you'll just end up with C++'ish code that just 
happens to be written in D.


D is not C++, and such premature optimizations might cause more 
harm if applied on occassion or out of habit.


IIRC D structs are all movable, so doing const refs here and 
there or using writing to ref parameter instead normal 
return(RVO) is likely bad for your code.


D has its own ABI, it's not even compatible with C++, so when you 
pass structs by value it may or may not produce similar asm as 
C++ compilers does.


When struct contains strings/arrays they are anyway managed by 
GC(unless you allocated it on your own), but this is something 
that more seasoned D users can explain in better details and 
cleaner explanation than me, if it means anything at all.


Even without all this, do you really want to mess up your 
codebase with implementation details about how it should do it, 
or write clean (self)documented code? Is it really going to be a 
bottleneck in your program? Passing one big struct at widget's 
creation on program startup and some rare events really going to 
kill performance?
Why not just write working code first and then identify 
bottlenecks and optimize when it absolutely ultimately necessary?
Btw I don't remember much ref parameters in phobos, just look at 
it... I found only 4 ref consts it in std.file, 3 in std.array, 
other modules more likely to have them in comparison operators(I 
have no idea why, to not introduce potential RVO case?) and in 
unit tests for testing correct behavior.


Again, D is not C++, what might work or even considered "good 
practice" there may or may not work here. So just profile it!




Re: How may I tell dub where to find a C library for linking?

2018-12-09 Thread evilrat via Digitalmars-d-learn
On Monday, 10 December 2018 at 02:59:21 UTC, Pablo De Nápoli 
wrote:


On my system (Debian GNU/Linux 9, 64 bits) the library is in 
the directory /usr/lib/llvm-6.0/lib/


$ ls -l /usr/lib/llvm-6.0/lib/libLLVM.so
lrwxrwxrwx 1 root root 14 oct 24 19:44 
/usr/lib/llvm-6.0/lib/libLLVM.so -> libLLVM-6.0.so


But how am I supposed to tell dub this, so it passes this 
information to the linker??


I guess I should set "libs" in dubs.json



IIRC your guess is correct. "libs" is passed directly to linker 
and is the only way to do it, so you just do smth like this


   "libs" : ["-L/usr/lib/llvm-6.0/lib/", "libLLVM-6.0"]

note that this -L will be extended for linker as -L-L...
(also note that you can do platform specific way with 
"libs-windows", "libs-posix"? to pick proper paths per platform)


Though I'm not a linux pro and don't remember if linking to .so 
is same as linking import library, if this is not the case you 
just need to set RPATH or whatever it is so it can find dynamic 
lib.


Re: DirectXMath alternative

2018-12-05 Thread evilrat via Digitalmars-d-learn
On Wednesday, 5 December 2018 at 10:52:44 UTC, Guillaume Piolat 
wrote:

On Wednesday, 5 December 2018 at 01:57:53 UTC, evilrat wrote:
On Tuesday, 4 December 2018 at 20:41:54 UTC, Guillaume Piolat 
wrote:
On Tuesday, 4 December 2018 at 20:33:07 UTC, John Burton 
wrote:
What is the best alternative for D, assuming there is 
anything?
(I want vector, matrix math for use in D3, things like 
inverting a matrix, getting perspective matrices etc)
I can program something myself if necessary but I'd prefer 
notto


You have the choice between the following packages:
- dlib
- gfm:math
- gl3n


I was using gl3n then switched to gfm math. Try gfm, IIRC it 
should work without much PITA because it stores matrices 
row-major way, so you don't have to transpose it like with 
OpenGL. Can't say anything about dlib though, I tried it a bit 
with dagon engine, but just didn't stick for long.


I think you are mistaken, gfm:math also stores matrices 
line-major so you _have_ to transpose them.


The problem with row-major is it makes matrix literals read 
transposed vs the math notation.


Are you sure you don't confuse lines with columns?
Here it says it is row major
https://github.com/d-gamedev-team/gfm/blob/master/math/gfm/math/matrix.d#L17



On Tuesday, 4 December 2018 at 20:41:54 UTC, Guillaume Piolat


I think in hlsl shader language you can declare your matrices 
to be either way anyway can't you? It's just the default that 
is this way around?


The only real difference is the order or operations. IIRC however 
gfm tries to hide this difference and use math notation.
Another thing is memory caches - accessing row in succession will 
have better chance of cached access while accessing columns in 
most(if not all) cases will fetch more items only to discard them 
on next value.

Though I haven't ever profiled this myself to be 100% sure.


Re: DirectXMath alternative

2018-12-04 Thread evilrat via Digitalmars-d-learn
On Tuesday, 4 December 2018 at 20:41:54 UTC, Guillaume Piolat 
wrote:

On Tuesday, 4 December 2018 at 20:33:07 UTC, John Burton wrote:

What is the best alternative for D, assuming there is anything?
(I want vector, matrix math for use in D3, things like 
inverting a matrix, getting perspective matrices etc)
I can program something myself if necessary but I'd prefer 
notto


You have the choice between the following packages:
- dlib
- gfm:math
- gl3n


I was using gl3n then switched to gfm math. Try gfm, IIRC it 
should work without much PITA because it stores matrices 
row-major way, so you don't have to transpose it like with 
OpenGL. Can't say anything about dlib though, I tried it a bit 
with dagon engine, but just didn't stick for long.


Re: Importing struct

2018-08-13 Thread evilrat via Digitalmars-d-learn

On Monday, 13 August 2018 at 13:09:24 UTC, Andrey wrote:

On Monday, 13 August 2018 at 13:05:28 UTC, evilrat wrote:
however the best option is simply avoid naming anything with 
same name as module.


Hmm, I thought that name of class should match name of file...

And how to name a file that contains only one class/struct? 
Like in my case. What usually true D coders do?)


Modules usually named after their purpose.

Like std.stdio for IO stuff, std.file for file utilities, and 
complex example is
std.algorithm.search for various searching algorithms which is a 
part of more global std.algorithm package (importing it also 
brings in several other std.algorithm.* modules).


Not sure about your use case, but seems like parser.d or args.d 
or argsparser.d (names best to keep lower case in case of OS or 
FS specific quirks, this is the convention)


Also if you need ready to use arguments parser check this one 
https://dlang.org/phobos/std_getopt.html


Re: Importing struct

2018-08-13 Thread evilrat via Digitalmars-d-learn

On Monday, 13 August 2018 at 12:44:44 UTC, evilrat wrote:



Another option to save up on typing is renamed imports

  import mc = MyClass;

  mc.MyClass.parse(...)



this also should work

  import mc = MyClass;

  alias MyClass = mc.MyClass; // make synonym

  // now it is just MyClass
  MyClass.parse(...)


however the best option is simply avoid naming anything with same 
name as module.


Re: Importing struct

2018-08-13 Thread evilrat via Digitalmars-d-learn

On Monday, 13 August 2018 at 12:34:25 UTC, Andrey wrote:

Hello,

This is my test project:
source/app.d
source/MyClass.d

app.d:

import std.stdio;
import MyClass;

void main(string[] args)
{
MyClass.MyClass.parse(args); // I want just 
MyClass.parse(args);

}


MyClass.d

import std.stdio;

struct MyClass
{
static void parse(string[] args)
{

}
}


In "main" function I need to write 
"MyClass.MyClass.parse(args)" bit I want just 
"MyClass.parse(args)". If I do so then I have an error:

Error: undefined identifier parse in module MyClass.

Of course function "parse" doesn't exist in this module. But it 
exists inside struct "MyClass"!

What should I do to import my struct correctly?


That's just name collision, because module is a valid symbol you 
need to be specific about what you are trying to access.


Try selective import instead

  import MyClass : MyClass;

Of course if there is more symbols needed you have to specify 
them as well after a comma.



Another option to save up on typing is renamed imports

  import mc = MyClass;

  mc.MyClass.parse(...)



Re: Windows 64-bit import library

2018-07-20 Thread evilrat via Digitalmars-d-learn

On Friday, 20 July 2018 at 04:31:38 UTC, Jordan Wilson wrote:

On Friday, 20 July 2018 at 01:34:39 UTC, Mike Parker wrote:

On Thursday, 19 July 2018 at 21:43:35 UTC, Jordan Wilson wrote:




Is there any way I can generate the appropriate lib?

Else I think I'll need to get hold of the proper import libs 
that come with the Lua distribution.


Lua is extremely easy to build. That will generate the import 
lib for you.


I don't have MSVC, so I built it using mingw, which generated a 
.a lib.
I shall google some more, as I understand it DMD -m64 uses 
Mingw libs as a fall back when MSVC not found, I compiled Lua 
using mingw, I can't be too much further away from being able 
to link in a 64-bit lua import lib in a 64-bit DMD compiled 
program...


what about passing your .def file directly with /DEF:your.def 
linker switch?


more info https://msdn.microsoft.com/en-us/library/34c30xs1.aspx


Re: Is there any tool that will auto publish my changes.

2018-07-16 Thread evilrat via Digitalmars-d-learn

On Sunday, 15 July 2018 at 00:25:22 UTC, Venkat wrote:
I am writing a simple vibe.d app. The following is what I do 
right now.


- I make changes.
- build
- Restart the server.

Is there any tool that will auto publish my changes as I save 
them ? I am using Visual Studio Code.


Thanks
Venkat


I don't think there are ready to use tools exists. But you can 
try to making (simple) one for your needs, for example using this 
package[1] to track file changes, then kill running instance, 
build and restart. Or doing the same with python/java/c#/whatever


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



Re: how to compile D programs without console window

2018-07-14 Thread evilrat via Digitalmars-d-learn

On Saturday, 14 July 2018 at 09:43:48 UTC, Flaze07 wrote:
On Saturday, 14 July 2018 at 09:39:21 UTC, rikki cattermole 
wrote:

If you're using dub, throw them into lflags and remove the -L.

https://forum.dlang.org/post/gmcsxgfsfnwllploo...@forum.dlang.org
hmm, for some unknown reason it says that it is unable to find 
SUBSYSTEM:windows.lib


/ (slash) is the part of a linker switch, /SUBSYSTEM:windows
so in dub.json it will look like

...
"lflags": [ "/SUBSYSTEM:windows" ],
...


Re: Create D binding for C struct containing templated class

2018-06-29 Thread evilrat via Digitalmars-d-learn

On Friday, 29 June 2018 at 06:04:10 UTC, Andre Pany wrote:


Thanks a lot for the great help.
You are right, until now I haven't looked at the include 
folder, I thought the "surface" folder is the folder with the 
public api. But it seems also in the include folder, the header 
files contains references to the grpc_call struct.

https://github.com/grpc/grpc/blob/master/include/grpc/impl/codegen/grpc_types.h#L70



It just declares new type(like forward declaration), so you 
should be able to do the same thing, or declare the actual struct 
with no members:

   struct grpc_call{}



Re: Create D binding for C struct containing templated class

2018-06-28 Thread evilrat via Digitalmars-d-learn

On Thursday, 28 June 2018 at 18:43:11 UTC, Andre Pany wrote:

Hi,

I try to write a binding for the GRPC core. There is a struct 
which has some ugly fields:

(https://github.com/grpc/grpc/blob/master/src/core/lib/surface/call.cc#L229)

struct grpc_call {
  gpr_refcount ext_ref;
  gpr_arena* arena;
  ...
  
grpc_core::ManualConstructor 
sending_stream;
  grpc_core::OrphanablePtr 
receiving_stream;



ManualConstructor is defined as:
https://github.com/grpc/grpc/blob/50cecca24d4826dea4595b514a332fca5783074b/src/core/lib/gprpp/manual_constructor.h#L168

template 
class ManualConstructor {
 public:
  Type* get() { return reinterpret_cast(_); }
  const Type* get() const { return reinterpret_castType*>(_); }



My C / C++ knowledge is very limited and I also do not know how 
much D matured regarding C / C++ integration. Is it possible to 
write a binding in D for these constructs or isn't it supported 
by D?


Kind regards
André


No, unfortunately D cannot interface with C templates, only C++ 
templates. But just by coincidence this is C++ source code (and 
so the templates).



So it is possible but there is few catches.
- template functions/methods could be inlined by compiler, which 
means you may (or may not) have to implement it in D (either 
copy-paste and adapt, or make own ABI compatible implementation)


- most of the methods in this particular template is purely C++ 
specific convenience helpers, all of this isn't strictly needed 
in D, just for example operator-> could simply be replaced with 
alias this.


- the only data member in this template is the 
std::aligned_storage, which you can probably ignore completely 
and instead just use fixed-size ubyte[] array with align, again 
just make struct with alias this and align its content same way 
as aligned_storage does.



And much more-more other things to keep in mind.


But the most important thing, are you absolutely sure this is a 
part of the public API and not the implementation specific 
internals? Because normally you don't #include anything other 
than .h* files, this is a source file, and it is not even sits in 
the include folder.


Re: Passing C++ class to DLL for callbacks from D (Steam)

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

On Sunday, 10 June 2018 at 01:35:40 UTC, cc wrote:

On Saturday, 9 June 2018 at 14:11:13 UTC, evilrat wrote:
However steam devs decided to shield actual pointer and return 
pointer sized integer when C API is used(or they just screw 
up?). Anyway, the pointers for subsystems returned by context 
calls on C++ API and mirrored C API calls are different, but 
they also have some mechanism for filtering this stuff, that 
way both integer handle and pointer calls the same underlying 
implementation, but C API call again is shielded so setting up 
CallResult and CCallback are ignored.



So my solution was just to make simple wrapper around C++ 
context calls and pass that real pointer to D side.


I see, thank you for checking it out.  Is it only the functions 
that return the interface pointers e.g. ISteamUserStats that 
need to be wrapped to use the class-based versions instead of 
the steam_api_flat versions?  Or does the entire callback 
system need to be handled through the wrapper?


Only subsystems getters like SteamUser() or SteamInventory() 
requires wrapping.


I really can't understand why they ever choose to silently ignore 
registering callbacks received with C API systems handles...


Re: Passing C++ class to DLL for callbacks from D (Steam)

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

On Saturday, 9 June 2018 at 03:14:13 UTC, cc wrote:

On Saturday, 9 June 2018 at 03:07:39 UTC, cc wrote:

I've put together a simplified test program here (124KB):


Here is a pastebin of the D source file updated with some 
additional comments at the end with the callback class 
definitions from the original header files

https://pastebin.com/M8hDXt6L


The proper bare minimum signature for call result callback is
--
extern(C++) abstract class CCallbackBase {
  abstract void Run( void *pvParam ) { writeln("Run()"); }
  abstract void Run( void *pvParam, bool bIOFailure, 
SteamAPICall_t hSteamAPICall );
  final int GetICallback() { return m_iCallback; } // this is 
actually optional

  abstract int GetCallbackSizeBytes();
 protected:
  uint8 m_nCallbackFlags; // probably can be left for some 
specific use cases

  int m_iCallback;
}
--
and the rest templates and stuff is purely for C++ convenience. 
Run(void*, bool, SteamAPICall_t) is what actually called for call 
result, then CallResult<> template overrides it to call 
appropriate pointer member in class with void (T::fun)(Data*, 
bool bIOFailure) signature.  You can mimic it on D side, or just 
ignore and make own.


There is one catch however, for it to be called flags should be 
equal 1, and iCallback must match struct enum, like 
NumberOfCurrentPlayers_t.k_iCallback for 
GetNumberOfCurrentPlayers()



However steam devs decided to shield actual pointer and return 
pointer sized integer when C API is used(or they just screw up?). 
Anyway, the pointers for subsystems returned by context calls on 
C++ API and mirrored C API calls are different, but they also 
have some mechanism for filtering this stuff, that way both 
integer handle and pointer calls the same underlying 
implementation, but C API call again is shielded so setting up 
CallResult and CCallback are ignored.



So my solution was just to make simple wrapper around C++ context 
calls and pass that real pointer to D side.


--- C++ code
// build as static library & link with your project
#ifdef _WIN32
// sorry, I just hardcoded it...
#pragma comment (lib, "steam_api64.lib")
#define _CRT_SECURE_NO_WARNINGS 1
#endif
  #include "public/steam/steam_api.h"
#ifdef _WIN32
#define _CRT_SECURE_NO_WARNINGS 1
#endif

extern "C" void* D_GetSteamUserStats()
{
  return SteamUserStats();
}

--- D code
// yes, I messed up with the signature to avoid casting, this may 
or may not be dangerous

extern(C) ISteamUserStats D_GetSteamUserStats();


This of course involves making C++ wrapper, but I don't really 
see other ways because they inlined everything ...


Re: Runtime introspection, or how to get class members at runtime Fin D

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

On Friday, 8 June 2018 at 08:06:27 UTC, Arafel wrote:

On Thursday, 7 June 2018 at 13:07:21 UTC, evilrat wrote:


I don't think so. It clearly states that children must mixin 
too, which can mean it just grabs symbols in scope only, and 
base class has no way of knowing about its subclasses. It also 
has "agressive mode" that will make metadata for all public 
symbols(?) it can walk, this may or may not be helpful 
depending on your requirements.




Yes, that's what I understood from looking at it, but perhaps I 
was just missing something. I wonder though how the "agressive 
mode" would work with separate compilation / dlopen'ed 
libraries. Perhaps I should give it a try and see what happens.


Besides there is no way(not that I am aware of) to make self 
registering stuff happen, you still need to call it somewhere. 
The most transparent option is probably just doing a mixin in 
each module that performs registration of all module symbols 
in module ctor.
The point is that there is absolute requirement to make 
explicit call for that, be it a module ctor mixin, class mixin 
or even user provided registration both at compile time or run 
time.
But since it is MIT licensed you can probably use the code as 
the starting point and adjust to your own needs.




BTW plug-ins is something that is right now possible on 
Linux(not sure about support on other *NIX systems), but in a 
very primitive form on Windows.
This is related to DLL support issues(such as type information 
not being passed across process/DLL boundaries), these issues 
also may include runtime issues as well such as inability to 
delegate the GC, which will mean there will be 2(or more) 
concurrent running GC's. But again I am not aware of the 
current situation.


Well, I'm already tightly coupled to linux, so this is not a 
big concern for me :-)


I'll keep trying, as I said, my intention was to let plugin 
writers do it as easily as possible, but well, adding some kind 
of "register" function might be necessary in the end...


A.


Yep. Like I said probably the easiest to use way is to place 
single call in each module. And there probably no other solution, 
because modules creates sort of isolated graph via imports. And I 
am not aware of any way to get list of modules passed in with 
compiler invocation to perform some sort of centralized one-liner 
registration.


But anyway look at this, might give some tips on how it can be 
done


mixin
https://github.com/Circular-Studios/Dash/blob/b7d589ad4ca8993445c136b6a4ae170932bb7962/source/dash/components/component.d#L208

(note that it uses static this() - module constructor. I think 
this behavior was changed around 2015-2016 and now it will cause 
cyclic dependency errors when modules with ctors import each 
other)


usage
https://github.com/Circular-Studios/Dash/blob/b7d589ad4ca8993445c136b6a4ae170932bb7962/source/dash/components/lights.d#L12



Re: Passing C++ class to DLL for callbacks from D (Steam)

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

On Friday, 8 June 2018 at 06:59:51 UTC, cc wrote:

On Friday, 8 June 2018 at 02:52:10 UTC, Mike Parker wrote:

On Friday, 8 June 2018 at 00:55:35 UTC, cc wrote:



class CImpl : CCallbackBase {
extern(C++) {


If anyone has any insight to provide it would be greatly 
appreciated, thanks!


I've not used any of the C++ interfacing features yet, but my 
understanding is the extern(C++) has to apply to the class 
declaration itself, not only the member functions:


extern(C++)
class CImpl : CCallbackBase {

Does that make a difference?


Tried wrapping the CImpl class in extern(C++), no luck.. tried 
final keyword on the methods too.  Thanks though.


Can you upload reduced example somewhere to play with?


Re: Passing C++ class to DLL for callbacks from D (Steam)

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

On Friday, 8 June 2018 at 00:55:35 UTC, cc wrote:


I've defined it in D, as per 
https://dlang.org/spec/cpp_interface.html#classes :




change this to class, or even abstract class as shown in example


extern(C++) {
interface CCallbackBase {
//this() { m_nCallbackFlags = 0; m_iCallback = 0; }
void Run( void *pvParam );
		void Run( void *pvParam, bool bIOFailure, SteamAPICall_t 
hSteamAPICall );

int GetICallback();
int GetCallbackSizeBytes();

		enum { k_ECallbackFlagsRegistered = 0x01, 
k_ECallbackFlagsGameServer = 0x02 }

//uint8 m_nCallbackFlags;
//int m_iCallback;
//friend class CCallbackMgr;

//CCallbackBase( const CCallbackBase& );
//CCallbackBase& operator=( const CCallbackBase& );
}
}


add extern(C++) to class as well to


class CImpl : CCallbackBase {
extern(C++) {
this() { m_nCallbackFlags = 0; m_iCallback = 0; }
void Run( void *pvParam ) { writeln("Run1"); }
		void Run( void *pvParam, bool bIOFailure, SteamAPICall_t 
hSteamAPICall ) { writeln("Run2"); }

int GetICallback() { return m_iCallback; }
		int GetCallbackSizeBytes() { return 
NumberOfCurrentPlayers_t.sizeof; } // ordinarily use templates 
to determine what type struct ptr to return

}
uint8 m_nCallbackFlags;
int m_iCallback;
}



you also may or may not need to mark non-virtual C++ methods as 
final.


Of course I haven't used D for quite some time so I can be 
mistaken.


But the lesson I learned the hard way is that in D for 
extern(C++) you don't use interface(it simply has no mapping to 
C++ types?), and for defining COM-interfaces use interface or it 
will bite you.

I hope it helps.



Re: Runtime introspection, or how to get class members at runtime Fin D

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

On Thursday, 7 June 2018 at 12:32:26 UTC, Arafel wrote:

Thanks for all the answers!

Is it possible to register, say, a base class, and have all the 
subclasses then registered automatically?


My idea would be to make it as transparent as possible for the 
plugin implementation, and also not having to depend on it.


A.



I don't think so. It clearly states that children must mixin too, 
which can mean it just grabs symbols in scope only, and base 
class has no way of knowing about its subclasses. It also has 
"agressive mode" that will make metadata for all public 
symbols(?) it can walk, this may or may not be helpful depending 
on your requirements.


Besides there is no way(not that I am aware of) to make self 
registering stuff happen, you still need to call it somewhere. 
The most transparent option is probably just doing a mixin in 
each module that performs registration of all module symbols in 
module ctor.
The point is that there is absolute requirement to make explicit 
call for that, be it a module ctor mixin, class mixin or even 
user provided registration both at compile time or run time.
But since it is MIT licensed you can probably use the code as the 
starting point and adjust to your own needs.




BTW plug-ins is something that is right now possible on Linux(not 
sure about support on other *NIX systems), but in a very 
primitive form on Windows.
This is related to DLL support issues(such as type information 
not being passed across process/DLL boundaries), these issues 
also may include runtime issues as well such as inability to 
delegate the GC, which will mean there will be 2(or more) 
concurrent running GC's. But again I am not aware of the current 
situation.


Re: Runtime introspection, or how to get class members at runtime Fin D

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

On Wednesday, 6 June 2018 at 13:28:02 UTC, Arafel wrote:


I know it might not be the most idiomatic D, but as somebody 
with mostly a Java background (with some C and just a bit of 
C++) it seems something really straightforward to me: 
myObject.getClass().getFields() [2].


Also, I know I could add some UDA or even crawl the modules and 
have this information generated automatically at compilation 
time and added to the type itself in a member, and I might even 
end up doing it, but honestly, I think it's something that the 
language should provide in a kind of easy / accessible way.


Powerful as compile-time introspection is, I think runtime 
shouldn't be forgotten either :-)


Thanks,

A.

[1]: https://dlang.org/library/object/type_info__class.html
[2]: 
https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getFields--


There is a library that creates reflection metadata for you. [1]

It seems a bit outdated and has some not-that-obvious compilation 
errors(for example getting ctor and callling it with runtime 
known type, or some other non template stuff), but other than 
that seems to be working (note that I didn't thorougly tested it, 
but its unittests succeeds on DMD 2.080 for both Windows x86 
mscoff & x64 )


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



Re: Making an .exe that executes source file inside itself.

2018-04-27 Thread evilrat via Digitalmars-d-learn

On Thursday, 26 April 2018 at 10:06:57 UTC, JN wrote:

On Wednesday, 25 April 2018 at 19:19:58 UTC, BoQsc wrote:

Alternatively, I don't know about specifics how to implement it 
in D, but the key phrase you are looking for is "code hotswap" 
or "hot loading". It's being popularized right now in gamedev 
circles, to avoid slow complications of the code. The way to do 
it is push code into DLLs, then reload the DLL if the change is 
detected. Of course it's not that simple, because there are 
some tricky parts around DLL boundaries and you have to reload 
the entire state, but it is possible. In such case, rather than 
recompile the entire code, you can just recompile a small 
subset of functionality to a DLL.


- content below is just my thoughts and may or may not have 
anything common with reality, don't take it as truth, forget 
after reading, proceed on your own risk



The overall process is like this:

1) make a core app that basically serves as host (whether or not 
put domain logic here is open question)
2) when run, scan & plug-in[*] shared libs (they must must follow 
well defined plugin API, ideally providing information about 
their requirements/dependencies and their services)
3) when library should be hot reloaded, it first serializes 
'shared' data, then re-loaded with same mechanism as in 2), and 
deserializes data back.


[*] - it has implications depending on platform, on Windows for 
example don't just load the libs(executing one's is locked by 
OS), but copy to temporary executing location first, that way one 
can overwrite the original libs while (a copy of) it is still 
running and app can be notified about file changes to perform hot 
reload.
(AFAIK UnrealEngine does this without temporary location, instead 
it relies on custom build system that checks whether app is 
running, which will then append incremental number to the name of 
the resulting binary, after build is done editor replaces old 
library with new one. I don't know the exact notification 
mechanism, it could be the build system itself or just FS event 
handled by engine which compares known running lib names for such 
incremental change, both ways makes it harder to manually replace 
library)




The one of the major points of having such libraries, after all, 
to be able to swap implementation without full rebuild, and 
better, in run time.
For example in case of game engine, let's say we want to switch 
rendering API(say DirectX to Vulkan), in this case there is even 
no need to serialize anything because most(if not any) of the 
stuff is implementation specific, such swap could be done 
*almost* in real time, I mean minor freeze for few frames doesn't 
makes a big difference here, and really I doubt anyone would do 
that in a middle of a game(not in menu or pause).


There is still lots of question, after all this is just example 
in theory, in practice however I've never yet come close enough 
to the practical implementation of such thing in D.


 WARNING: ONLY WINDOWS-SPECIFIC STUFF BELOW

But now the problem.
Guess what? DLL support on Windows is simply isn't there yet! 
AHAHAHAH (imagine some epic evil laugh here)


Sure thing, it is possible to make a bunch of loose functions 
that operates on built-in (value) types, but does this really 
provides the extensibility? I can hardly imagine usefulness of 
such approach in any but trivial cases, just imagine Unity or 
Unreal Engine, or complex software like 3ds Max or Maya...
It is also to some extent possible to go shady with hacks and 
abuses, but this is something that should not be shipped as 
production ready, and there is even no guarantee it will work in 
a future.
The last option probably is to implement whole mechanism from 
scratch, like COM objects, D is a system language after all, but 
I to be honest don't have the desire to fall that low, especially 
because on Linux it works for years...


(side note: I actually tried few simple (hacky) test cases with 
passing classes cross-boundary and then unloading library, seems 
to work on Windows, not sure about memory leaks and consequnces 
in long runs though)


Re: Request Assistance Calling D from C++: weird visibility issue inside struct and namespace

2017-11-07 Thread evilrat via Digitalmars-d-learn
On Wednesday, 8 November 2017 at 06:34:27 UTC, Andrew Edwards 
wrote:


Modify example.cpp to:

==
// example.cpp
#include "example.h"
namespace SomeApi {}
struct SomeStruct {}
void call_cpp() {
foo("do great things");
return;
}
==




Compile and link and you have D program calling, calling C++, 
which in turn calls D.


My problem is that I've encountered an issue where this does 
not work: when the function is being called from a namespace or 
local scope in C++, the linker cannot find the definition. For 
example:




just using fully qualified name didn't make it?

void call_cpp() {
::foo("do great things"); // calling global foo
return;
}



In a last-ditch effort, I placed all of these definitions into 
dexample.d and, it compiled, but still filed to linking:




Are you sure you put it in a namespace in C++ too?

otherwise there might be some name mangling incompatibility that 
probably worth filling a bug report




Re: COM/OLE advanced questions

2017-11-02 Thread evilrat via Digitalmars-d-learn
You'd better read some more authorative source since my 
experience is very limited on that matter, but here is some quick 
notes


On Thursday, 2 November 2017 at 14:22:56 UTC, Guillaume Piolat 
wrote:


Question 1. Is it mandatory to inherit from 
core.sys.windows.unknwn.IUnknown, or just having an interface 
named "IUnknown" validate it for being a COM interface?


   If yes, then how am I supposed to use COM interfaces in 
other OSes? core.sys.windows.unknwn.IUnknown is defined under 
version(Windows).


   I wonder what the exact compiler hook is.



You can't(or maybe you can but that is not a true COM). COM is 
Windows tech. It is backed up by OLE or whatever server it is.


My guess it will work fine when derive from any extern(Windows) 
interface(that's right, not class) that has base 3 
methods(AddRef, Release, QueryInterface)


It is also tied to a Windows registry, since to be able to create 
COM objects using CoCreateInstance its class factory has to be 
registered with class id (CLSID), then IIRC, for example in C# 
creating a COM object instance(using new) makes corresponding 
lookup by GUID to retrieve CLSID and CoCreateInstance calls that 
factory to make an object.
But you don't have to use COM mechanincs on your COM enabled 
classes inside your code.


Now there can be a problem, say for example you want to make a 
COM class in D for external usage, most likely you will have to 
make interface first, then derive a class for actual 
implementation, because class will add stuff to vtable and break 
order. (just a guess)




Question 2. If this fails, may I emulate COM vtable layout with 
extern(C++) class? I wonder what the exact differences are 
anyway between extern(C++) and the special IUnknown.




I don't know the exact internals mechanics, but yes, not sure if 
extern(C++) will work though. COM can be used from C, and so COM 
methods is basically a C function that takes object as first 
argument, so on C++ side it is flavored to make a vtable and 
respective method calls(or vice versa, depending how the specific 
class implemented). (like I said, find some better read on this)


Also since it can be implemented in C, and that requires manually 
making COM vtable in there(IIRC with an array), you can just do 
the same in D.




Question 3. It seems I can inherit both from A D object and a 
COM interface. What will be the choosen layout?




like I said in Q2, if your goal is to make COM class accessible 
by other languages then make interface derived from IUnknown(or 
any other COM interface you like) and fill in the methods, but 
implement them in derived from that interface class. (again, just 
a guess, because of vtable shifting) and don't forget, on Windows 
you also must register a class factory (see 
IClassFactory.CreateInstance) to be able to create objects from 
other COM clients.




Re: dub optional dependency

2017-10-28 Thread evilrat via Digitalmars-d-learn

On Saturday, 28 October 2017 at 19:23:42 UTC, ikod wrote:


So default version is "std", I can build it w/o vibe-d, but dub 
anyway fetch  vibe-d.

I'd like dub fetch vibe-d only when I build with --config vibed.

I know about "optional": true, it prevent dub to fetch vibe-d 
for "std" config, but it also prevent it from fetching for 
--config vibed.




This is dub design choice, optional requires manual fetching(dub 
fetch 'package'). I don't see other options, but you can try hack 
this using 'preBuildCommands' by adding dub fetch. Of course this 
defeats the purpose.


Isn't it possible to put dependencies in specific configuration?


  1   2   >