Re: Window created with Windows API is not visible

2022-06-18 Thread Adam Ruppe via Digitalmars-d-learn

On Saturday, 18 June 2022 at 23:00:36 UTC, solidstate1991 wrote:

This is going to be a long match.


you might consider using another exisitng lib. my simpledisplay.d 
does all this and much more for example


Re: Comparing Exceptions and Errors

2022-06-04 Thread Adam Ruppe via Digitalmars-d-learn
On Saturday, 4 June 2022 at 22:31:38 UTC, Ola Fosheim Grøstad 
wrote:
So what do you have to do to avoid having Errors thrown? How do 
you make your task/handler fault tolerant in 100% @safe code?


Run it in a separate process with minimum shared memory.


Re: What happened to Deimos and why ?

2022-06-04 Thread Adam Ruppe via Digitalmars-d-learn

On Saturday, 4 June 2022 at 13:44:06 UTC, Alain De Vos wrote:

What happened to Deimos and why ?


Nothing, it does its job same as it always has.


Re: How to fix "typesafe variadic function parameter"?

2022-05-24 Thread Adam Ruppe via Digitalmars-d-learn

On Tuesday, 24 May 2022 at 22:46:55 UTC, Andrey Zherikov wrote:

return S(s);


return S(s.dup);


The variadic lives in a temporary array that expires at the end 
of the function. So copying it out to the GC lets it live on.


Your code was wrong on 2.099 too, but the compiler didn't tell 
you.




Re: Cannot check function address

2022-05-24 Thread Adam Ruppe via Digitalmars-d-learn

On Tuesday, 24 May 2022 at 18:54:33 UTC, frame wrote:
Usually that works fine as shown in module A but for some 
reason not in module B.


Do you have some other definition of fun somewhere?


Re: How to call destroy() in @nogc?

2022-05-24 Thread Adam Ruppe via Digitalmars-d-learn
On Tuesday, 24 May 2022 at 14:11:57 UTC, Steven Schveighoffer 
wrote:
Note it has no idea what the real object type is at this point, 
just that it is an Object (which does not have a @nogc 
destructor).


It actually has nothing to do with Object. It doesn't have a 
destructor at all, so there's no problem calling it from any 
context.


The real problem is that destructors don't actually use the 
virtual machinery and call super(), meaning it is impossible to 
tell at compile time what they're doing at all.


I know I wrote at length about this somewhere but can't find it 
right now. Probably in the chatroom. But even if you know static 
type, you can't make assumptions about the dynamic type since 
destructors (for no good reason tbh) don't follow the same rules 
as other virtual methods, despite the spec saying they are 
virtual.


Re: Error: undefined symbol: _WinMain@16 When try compile no console

2022-05-19 Thread Adam Ruppe via Digitalmars-d-learn

On Thursday, 19 May 2022 at 21:41:50 UTC, Marcone wrote:
Are you using the `-L/entry:mainCRTStartup` or the 
`L/entry:wmainCRTStartup` ?


-L/entry:mainCRTStartup


try the w one too. both doing the same result?


Re: Library for image editing and text insertion

2022-04-26 Thread Adam Ruppe via Digitalmars-d-learn

On Tuesday, 26 April 2022 at 18:31:49 UTC, H. S. Teoh wrote:
maybe look at Adam Ruppe's arsd library 
(https://github.com/adamdruppe/arsd) for some lightweight 
modules that read common image formats and do some primitive 
image manipulations.


I don't actually have an image to image blit function, but 
writing one is trivial - just loop over it and call alphaBlend.


It can load ttf fonts, render them to bitmaps, load images, 
combined them, then save images. Can even load ttfs off the 
operating system if you wanted to use those or even have the 
OS functions do the drawing instead of diy, but probably easier 
to diy this simple case.


Sample code would be:

---
import arsd.image;
import arsd.ttf;

void main() {
auto image = loadImageFromFile("/home/me/small-clouds.png");
if(image is null)
throw new Exception("Couldn't load the image file");
	auto tci = image.getAsTrueColorImage(); // convert to rgba for 
simplicity


import std.file;
	auto font = TtfFont(cast(ubyte[]) 
std.file.read("/home/me/arsd/sans-serif.ttf"));


int width, height;
	auto bitmap = font.renderString("Hello", 14, width, height); // 
it populates width and height fyi


// where we want to put it
int xput = 30;
int yput = 20;

int bitmapOffset = 0;

// color to draw the text
int r = 255;
int g = 0;
int b = 0;

foreach(y; 0 .. height) {
if(y + yput >= image.height)
break;
foreach(x; 0 .. width) {
			scope(exit) bitmapOffset++; // always advance this as long as 
we're still drawing...

// but don't draw out of bounds
if(x + xput >= image.width)
continue;

// replace a pixel with the blended version of the text 
bitmap
image.setPixel(
xput + x, yput + y,
image.getPixel(xput + x, yput + y).
alphaBlend(Color(r, g, b, 
bitmap[bitmapOffset]))
);
}
}

import arsd.png;
writePng("text-image.png", image); // save it back to a png
}
---


Open the text-image.png to see the result. (Or:
---
import arsd.simpledisplay;
displayImage(Image.fromMemoryImage(image));
---
to display it in a window right from your program!)



My libs are available as individual files from the github - you 
might just use png instead of the whole image.d to avoid needing 
additional files for formats you don't need - or you can pull it 
on dub under the arsd-official:image_files package and 
arsd-official:ttf.


Re: A template construct like using()

2022-04-26 Thread Adam Ruppe via Digitalmars-d-learn

On Tuesday, 26 April 2022 at 23:00:57 UTC, cc wrote:
If your draw code doesn't depend on any scoped state you can 
use `function()` instead of `delegate()` to save a GC call.


`scope delegate` also works here and just reuses the stack.




Re: Beginner memory question.

2022-04-16 Thread Adam Ruppe via Digitalmars-d-learn

On Saturday, 16 April 2022 at 20:41:25 UTC, WhatMeWorry wrote:

Is virtual memory entering into the equation?


Probably. Memory allocated doesn't physically exist until written 
to a lot of the time.


Re: TIC-80 WebAssembly: pointers to fixed addresses

2022-04-16 Thread Adam Ruppe via Digitalmars-d-learn

On Saturday, 16 April 2022 at 14:29:09 UTC, Pierce Ng wrote:

```
pub const FRAMEBUFFER: *allowzero volatile [16320]u8 = 
@intToPtr(*allowzero volatile [16320]u8, 0);

pub const TILES : *[8192]u8 = @intToPtr(*[8192]u8, 0x4000);
pub const SPRITES : *[8192]u8 = @intToPtr(*[8192]u8, 0x6000);
```

I believe the above is declaring that FRAMEBUFFER is a pointer 
to 16320 (sic) bytes starting at address 0, TILES is a pointer 
to 8192 bytes starting at address 0x4000, and SPRITES a pointer 
to 8192 bytes starting at address 0x6000.


Currently for D I have the following, copying the D binding for 
Wasm4, another fantasy console:


```
const FRAMEBUFFER = cast(uint*)0;
const TILES = cast(uint*)0x4000;
const SPRITES = cast(uint*)0x6000;
```

How to express in D, similarly to Zig, that FRAMEBUFFER refers 
to a byte[16384] array starting from address zero, and so on?


Take the pointer and slice the pointer:

__gshared ubyte[] framebuffer = (cast(uint*) 0) [0 .. 16320]; // 
gshared cuz otherwise D assumes it is TLS and it isn't



Now you can notice it isn't const. You don't want it const since  
the point is to write to the thing. What you might do to keep the 
pointer itself from ever changing is to make it a property:



ubyte[] framebuffer() { return (cast(uint*) 0) [0 .. 16320]; }


And the compiler will see how trivial that is and inline it so it 
works the same way, but then nobody can ever rebind the 
framebuffer symbol.


Re: arsd.minigui

2022-04-03 Thread Adam Ruppe via Digitalmars-d-learn

On Sunday, 3 April 2022 at 16:58:03 UTC, JG wrote:

Hi,

I have an png image that I generate (via pdf via pdflatex) that 
I want to scale and display in a widget. Is this possible via 
something in arsd? I tried resizeImage but that doesn't seem to 
do what I expect. Any suggestions?


Which resizeImage did you use, from the imageresize module? What 
pain you have with it? Some of its settings take some tweaking.


Though in a widget, you can also stretch automatically on 
Windows... actually XRender can do it too i believe but I never 
implemented that. Maybe I should.


But imageresize should work with some experimentation. This is 
how I did it in my image viewer application:



   auto i = loadImageFromFile(arg);

auto size = 
calculateSizeKeepingAspectRatio(i.width, i.height, maxWidth, 
maxHeight);
if(size.width != i.width || 
size.height != i.height) {
i = imageResize(i, 
size.width, size.height, null, 1.0, 0.6);

}


then pass that i to one of the minigui/simplediplay functions to 
display.


Re: arsd-minigui - couple of questions

2022-03-28 Thread Adam Ruppe via Digitalmars-d-learn
In fact, using a pragma now, I think I got it so you don't even 
need the manifest now (the pragma includes a default one now).


Only works when doing dmd -m32mscoff or dmd -m64 builds (which 
are also what dub uses fyi), will NOT work with a default dmd 
no-switch build.


Re: arsd-minigui - couple of questions

2022-03-28 Thread Adam Ruppe via Digitalmars-d-learn
oooh it actually is even easier than I thought, just a changed 
flag plus the manifest.


Just pushed to minigui master. only ended up being 4 lines for 
this little thing.


Try rebuilding with that AND be sure to use the manifest file 
too, same as dwt. Then you should be able to find some joy.


Re: arsd-minigui - couple of questions

2022-03-28 Thread Adam Ruppe via Digitalmars-d-learn

On Monday, 28 March 2022 at 21:10:47 UTC, Sai wrote:
FWIW, DWT which uses native controls on windows can show 
transparent pngs and also both image & text at the same time. 
However I had to add the following app.exe.manifest


Yeah, this tells me they used owner-drawn buttons, which is only 
supported if you use version 6 controls. The version 6 controls 
are nice btw even if you don't use this specific feature, they 
also come with automatic theme support and a few other nice 
things. I actually recommend in the docs that you use this for 
simpledisplay/minigui applications too, just then you also need 
to provide a draw method to do the text+image.


It isn't hard to do, about a dozen lines for this basic case that 
you can just opt into and use the default draw for other cases.


I was thinking about adding one of those anyway (another nice 
thing you can do is change the background color), I just haven't 
gotten around to it yet. Maybe I'll do it tomorrow.


Keep an eye on this thread, if I do, I'll let you know.



Re: arsd-minigui - couple of questions

2022-03-28 Thread Adam Ruppe via Digitalmars-d-learn

On Monday, 28 March 2022 at 17:00:42 UTC, sai wrote:
1. I assume arsd-minigui library does not support transparent 
images by itself, does it? I am trying to show a png image with 
transparent areas on a button, but those transparent areas 
shows as black color.


Well, I tried forwarding the flag, I can custom draw it this way 
but the standard Windows button's normal draw doesn't appear to 
care...


There might be a trick I just don't know, but the problem is I 
don't know it lol.





Re: arsd-minigui - couple of questions

2022-03-28 Thread Adam Ruppe via Digitalmars-d-learn

On Monday, 28 March 2022 at 17:00:42 UTC, sai wrote:
1. I assume arsd-minigui library does not support transparent 
images by itself, does it? I am trying to show a png image with 
transparent areas on a button, but those transparent areas 
shows as black color.


I added that to simpledisplay last year, but never forwarded the 
flag to minigui since it didn't seem important should be easy 
enough to add, I'll take a look.


2. I want to show both image and text on a button, but looks 
like it shows image or text, but not both at the same time. Or 
am I missing some weird windows manifest stuff?


Yeah, it is one or the other right now. I don't think the 
standard Windows control supports that without owner draw, which 
is something I've generally tried to avoid (but it isn't that 
hard to do at least in some cases...).


Re: Basic question about size_t and ulong

2022-03-18 Thread Adam Ruppe via Digitalmars-d-learn

On Friday, 18 March 2022 at 21:54:55 UTC, WhatMeWorry wrote:

Isn't ulong an integer? And isn't memory addresses 64 bits long?


Only if you are doing a 64 bit build. Try using -m64


Re: static init c struct with array filed

2022-03-16 Thread Adam Ruppe via Digitalmars-d-learn

On Thursday, 17 March 2022 at 00:16:39 UTC, Mike Parker wrote:

On Wednesday, 16 March 2022 at 07:27:06 UTC, test wrote:

```c
struct Test {
int32_t a;
}
struct Test2 {
int32_t a;
Test arr[];
}
```

I need static const init Test2, then pass it to c library 
late(third library, can not change the type def).




Any time you see a '[]' in C, the equivalent declaration in D 
has to be a pointer.


Not always with structs... if it has a fixed size or an 
initializer in C, then you need to match the size in D.


Otherwise yeah use the pointer.



Re: forward tuple arg to local variable + dtor

2022-01-22 Thread Adam Ruppe via Digitalmars-d-learn
You can't forward to a local variable. Local variables will be a 
copy of the tuple. forward only actually works if sent *directly* 
to another function call.


There's a bunch of things in D that only work in function 
parameter lists and not local variables. This is one of them.


Re: Using getSymbolsByUDA in a static foreach loop

2022-01-19 Thread Adam Ruppe via Digitalmars-d-learn

On Thursday, 20 January 2022 at 00:55:33 UTC, Jack Stouffer wrote:
static foreach(member; __traits(allMembers, 
Manager))


member here is a string, not the member. I prefer to call it 
memberName.


Then you __traits(getMember, Manager, memberName) to actually get 
the alias you can pass to getAttributes.


Re: Ambiguity issue with expanding and evaluating single template type parameter enums

2021-12-27 Thread Adam Ruppe via Digitalmars-d-learn
On Tuesday, 28 December 2021 at 00:13:13 UTC, data pulverizer 
wrote:
There are various requirements, sometimes I have to cast or 
type convert, so I **need** the type to paste correctly and 
explicitly.


You almost never actually need types as strings. I'm almost 
certain there's a better way for you to get the same work done.


Have you tried just using T directly in your mixin? You can 
frequently just use the local name and skip the string getting 
entirely.


Re: Ambiguity issue with expanding and evaluating single template type parameter enums

2021-12-27 Thread Adam Ruppe via Digitalmars-d-learn
On Monday, 27 December 2021 at 21:21:30 UTC, data pulverizer 
wrote:

  alias T = MyType!(INTEGER);


What is MyType?


  enum code = "writeln(\"instance: \", adder(" ~
  T.stringof ~ "(), " ~ U.stringof ~ "()" ~ "));";


And why is this a string mixin instead of a plain simple function?

prolly need more context


Re: Ambiguity issue with expanding and evaluating single template type parameter enums

2021-12-27 Thread Adam Ruppe via Digitalmars-d-learn
On Monday, 27 December 2021 at 21:05:51 UTC, data pulverizer 
wrote:

adder(MyType!MyEnum.INTEGER(), MyType!MyEnum.STRING());


The rule for !(args) is of you leave the parenthesis off, it only 
uses the next single token as the argument. So it will never 
include a dot; it is like you wrote `MyType!(MyEnum).INTEGER`.


You might just always use the () in your generated code when 
you create that mixin string can't just just change the generator 
to put the () around it? Or is the stringof generating this? 
(Another reason why stringof is terrible and should never be used 
ever for anything.)


`MyType!MyEnum.STRING` is generated with `T.stringof `. I get 
the error:


if you can paste teh code where you generate this I can prolly 
show you a much easier way to do it. stringof sucks really hard.


Re: How to print unicode characters (no library)?

2021-12-26 Thread Adam Ruppe via Digitalmars-d-learn

On Sunday, 26 December 2021 at 20:50:39 UTC, rempas wrote:
I want to do this without using any library by using the 
"write" system call directly with 64-bit Linux.


write just transfers a sequence of bytes. It doesn't know nor 
care what they represent - that's for the receiving end to figure 
out.


know (and tell me if I'm mistaken), UTF-16 and UTF-32 have 
fixed size lengths for their characters.


You are mistaken. There's several exceptions, utf-16 can come in 
pairs, and even utf-32 has multiple "characters" that combine 
onto one thing on screen.


I prefer to think of a string as a little virtual machine that 
can be run to produce output rather than actually being 
"characters". Even with plain ascii, consider the backspace 
"character" - it is more an instruction to go back than it is a 
thing that is displayed on its own.


Now the UTF-8 string will report 11 characters and print them 
normally.


This is because the *receiving program* treats them as utf-8 and 
runs it accordingly. Not all terminals will necessarily do this, 
and programs you pipe to can do it very differently.


Now what about the other two? I was expecting UTF-16 to report 
16 characters and UTF-32 to report 32 characters.


The [w|d|]string.length function returns the number of elements 
in there, which is bytes for string, 16 bit elements for wstring 
(so bytes / 2), or 32 bit elements for dstring (so bytes / 4).


This is not necessarily related to the number of characters 
displayed.


Isn't the "write" system call just writing a sequence of 
characters without caring which they are?


yes, it just passes bytes through. It doesn't know they are 
supposed to be characters...




Re: How to pass a class by (const) reference to C++

2021-12-15 Thread Adam Ruppe via Digitalmars-d-learn

On Wednesday, 15 December 2021 at 22:24:42 UTC, H. S. Teoh wrote:
`__gshared` is needed to coax the compiler into making the 
variable global in the C/C++ sense, i.e., only 1 instance 
across all threads.



it is just normally __gshared implies static automatically. it 
does in like every other context but i guess not in the mangler 
or whatever.


Re: Why code failed to compile for foo2?

2021-12-11 Thread Adam Ruppe via Digitalmars-d-learn
On Saturday, 11 December 2021 at 23:17:17 UTC, Stanislav Blinov 
wrote:
? No. If it was unsatisfied constraint, the error would've 
shown that.


And if you try to instantiate it, you'll see it is an unsatisfied 
constraint anyway. There's two layers of failure here.


Using Unqual there is pretty iffy, i wouldn't bother with it at 
all, but if you do anything, instead qualify it const.


But either way, then the constraint still fails since int isn't 
unsigned.


I'd really recommend simplifying this a lot.


Re: Why code failed to compile for foo2?

2021-12-11 Thread Adam Ruppe via Digitalmars-d-learn

On Saturday, 11 December 2021 at 22:50:45 UTC, apz28 wrote:

void foo2(T)(Unqual!T x) if(isUnsigned!T) {}


This means it treats foo2 as if it doesn't exist unless T is 
unsigned...


onlineapp.d(15): Error: template `onlineapp.foo2` cannot deduce 
function from argument types `!()(int)`

onlineapp.d(7):Candidate is: `foo2(T)(Unqual!T x)`
*/


And this is telling you it had a signed value - int - which means 
it doesn't match.


For the other ones, the functions still exist, so it does 
whatever conversion it needs. Whereas with the template that 
constraint means the compiler acts like it doesn't exist at all 
and thus doesn't even attempt an automatic conversion.


Re: T... args!

2021-12-08 Thread Adam Ruppe via Digitalmars-d-learn

On Wednesday, 8 December 2021 at 23:43:48 UTC, Salih Dincer wrote:

Is this not a contradiction? : and 3.1415 aren't string:

```d
void foo(string...)(string args) {


`string...` there is a user-defined identifier representing a mix 
of types.


string isn't special, yo can declare your own variables with that 
name. And that's what you did here.


I think you meant to say

void foo(string[] args...) {}

which is avariadtic number of only strings


Re: How to read a single character in D language?

2021-11-19 Thread Adam Ruppe via Digitalmars-d-learn

On Friday, 19 November 2021 at 20:51:09 UTC, BoQsc wrote:

But the source file overwhelmed me by its size.


Yeah, the getch function in there builds on the rest of the 
events the library offers, so it won't be that useful outside.



The OS functions for getch alone though are actually pretty 
simple:


1) change the terminal to "raw" mode. the default is to buffer 
lines, which means your application doesn't get anything until a 
line is complete. You need to turn that off.


The RealTimeConsoleInput constructor does this in the lib:
http://arsd-official.dpldocs.info/v10.3.8/source/arsd.terminal.d.html#L2487

On Windows, you basically just call `SetConsoleMode`, but since 
the console is a shared resource, you also need to save the old 
mode to set it back later (that's what I do in the destructor of 
the struct).


On Linux, you call `tcsetattr`. The function for mine is here:
http://arsd-official.dpldocs.info/v10.3.8/source/arsd.terminal.d.html#L2620

Again, the terminal is a shared resource (this is actually even 
more true on linux systems!) so it is important to save the old 
one and set it back when you're done. There's a lot of ways this 
can happen so you should handle them all - that's why there's a 
bunch of signal handler blocks there.


Other things the library initialize is if you want echo, mouse 
input, paste events, resize notifications, etc. But if you only 
care about getch you can ignore most that stuff.


2) Read the terminal's event stream. On Windows, you call 
`ReadConsoleInput` and process the struct it sends you for a 
keyevent. See: 
http://arsd-official.dpldocs.info/v10.3.8/source/arsd.terminal.d.html#L3122


On Linux, you call the system `read` function on the stdin stream 
(file number 0). Basic keys will come as a single byte read on 
there. Others get extremely complicated.

http://arsd-official.dpldocs.info/v10.3.8/source/arsd.terminal.d.html#L3369

And it goes on for about 400 lines! And it depends on some of 
that other initialization we skipped over before and uses a 
database of terminal quirks found elsewhere in the file.


Windows' API is far, far easier to use.


But the Linux one isn't bad if you only want basic alphanumeric 
and enter keys. You can read those as a single ascii byte off the 
read function, so for that you can do it in just a few lines.


3) Again, remember to set it back how you found it before you 
exit by callling the SetConsoleMode/tcsetattr again before you 
exit.


Re: arsd.simpledisplay on macos

2021-11-16 Thread Adam Ruppe via Digitalmars-d-learn

On Tuesday, 16 November 2021 at 03:41:31 UTC, Ben Jones wrote:
I'm trying to use Adam's simpledisplay on a mac with XQuartz 
which is installed + running.  When I try to create a window, 
it crashes when calling `XDisplayConnection.get()`.


Hmm, I have never actually seen that fail since the mac will 
start up the X server on demand.


Nevertheless, you might want to try a few things:

1) run xquartz separately to ensure it is up
2) set hte DISPLAY=:0 environment variable before starting the 
sdpy app
3) also perhaps try DISPLAY=127.0.0.1:0 in case it isn't 
configured for it



Also possible I bugged it since then though, since it dynamic 
loads the libs instead of static and I never actually tested that 
fully on mac. But I think if that was the case you'd get an abort 
instead of an exception; it wouldn't get to the connection failed 
step.


r is there an example that seems to work with the native cocoa 
version?  I'm only planning to use really basic functionality 
(display an image and maybe capture some key presses)


I actually don't think the key press functions work anymore, but 
they are probably fairly easy to fix.


You have to build it without dub so you can pass 
-version=OSXCocoa to the compiler. Then some things at least 
should work.


But the Cocoa implementation was contributed to me back in like 
2012 and I've spent very little time on it since then. At one 
point last year, I did get its window working again at least but 
not much else. It is liable to throw NotYetImplementedExceptions 
and might have regressed since then too.


I have a mac vm i set up but it is a pain to use so I rarely 
bother


Also, Adam, if you have an idea of what needs to be done to get 
native macos support working, I'm willing to try to give it a 
shot.


So the existing code is an implementation of just the basic 
featureset built on extern(C) objc_msgSend calls. It is really 
ugly code and nothing I've added since 2012 works in there at all 
- anything more than the basic timer is not implemented, no file 
events, no opengl, no fonts. Even basic window methods probably 
won't work like maximize and show.


What I'd really like to do is to use dmd's beautiful 
extern(Objective-C) interface to make the code easier to use. I 
was kinda hoping those would be added to druntime like 
core.sys.windows but apparently not. ldc hasn't even implemented 
the feature at all :( (ive been considering porting it from dmd 
to ldc myself for like 2 years but it is super low priority since 
in the rare times i use a mac, im ok with the X server)


But yeah I don't know much about mac development and have a 
trillion other things to do.


Re: D modules

2021-11-13 Thread Adam Ruppe via Digitalmars-d-learn

On Saturday, 13 November 2021 at 22:52:55 UTC, pascal111 wrote:
When I'm searching for "toUpper" and "toLower" functions that 
string type uses


They are usable though `import std.string;` the docs just don't 
do a great job showing that.


The newest test version of my doc generator does integrate them 
into the member list though:


http://dpldocs.info/experimental-docs/std.string.html

My dpldocs.info website has a search engine too to help find the 
original place:


dpldocs.info/toLower

for example will point you at std.uni first.

But if it is "public imported" into a member list of another 
module you can use it just importing either way.


Re: in a template, how can I get the parameter of a user defined attribute

2021-11-06 Thread Adam Ruppe via Digitalmars-d-learn

On Saturday, 6 November 2021 at 19:45:49 UTC, Chris Bare wrote:

dbForeignKey!(Position)



static if(is(T == dbForeignKey!Arg, Arg)) {
   // use Arg here
}



Re: How to do a function pointer to "malloc" and "free"?

2021-10-17 Thread Adam Ruppe via Digitalmars-d-learn

On Sunday, 17 October 2021 at 23:07:15 UTC, Elmar wrote:
Do you have a link for more information how to initialize the D 
runtime?


Export a function that calls this:
http://druntime.dpldocs.info/core.runtime.Runtime.initialize.html

And also export a function that calls this:
http://druntime.dpldocs.info/core.runtime.Runtime.terminate.html

And tell the user to call those when they load/unload the 
library. (It is pretty common for C libraries to require explicit 
init/term calls so they should be used to it.)


They refcount internally so it is ok to call multiple times, just 
make sure the init and term are always paired.




(btw the druntime actually exports them as extern(C) 
rt_init/rt_term but I'd still recommend you do your own anyway. 
if you do have extra work to do you can just do it there, and it 
can use whatever your lib naming conventions are. and besides im 
not sure if the extern(C) things are specified stable (even 
though they have been for as long as i can remember), whereas 
doing your own thing that `import core.runtime; return 
Runtime.initalize;` is. )


Re: How to do a function pointer to "malloc" and "free"?

2021-10-10 Thread Adam Ruppe via Digitalmars-d-learn

On Sunday, 10 October 2021 at 13:52:57 UTC, Elmar wrote:
The language subset "BetterC" is required for calling D 
functions from C though.


This is false.

You can use any D features when calling it from C, you just need 
to provide an init and term function that is called from C that 
runtime initialize and terminate for the full experience.



BetterC helper librarys like Tanya or Tango do exist.


I don't know tanya, but Tango has absolutely nothing to do with 
betterC. It is a set of classes that use the full runtime.


Re: Better debugging?

2021-10-03 Thread Adam Ruppe via Digitalmars-d-learn

On Sunday, 3 October 2021 at 22:21:45 UTC, Tim wrote:

 -gc DMD2 compiler switch


tried plain -g ?

-gc is a compatibility debug thing for things with zero D 
support. p oboslete now


Re: Template mixin problem with EnumMembers

2021-10-02 Thread Adam Ruppe via Digitalmars-d-learn
On Saturday, 2 October 2021 at 22:07:23 UTC, Ferhat Kurtulmuş 
wrote:
The below code works as expected on https://run.dlang.io/, but 
not on my computer. And I don't know why?


You used .stringof. That's undefined behavior. Never use 
stringof. (except for debugging writes)


Now, I'd actually probably do this entirely differently... just 
using opDispatch.


```
class Options{
public:

enum StringOption {
OUT_FILE_NAME,
RPT_FILE_NAME,
MAP_FILE_NAME
}

static template opDispatch(string name) 
if(__traits(hasMember, StringOption, name)) {
alias opDispatch = __traits(getMember, StringOption, 
name);

}
}
```

and done. (even that `if` template constraint isn't really 
necessary and im usally anti-those too, but here it kinda makes 
sense. in theory. in practice it makes zero difference, but in 
theory, if the dmd regression that broke these error messages 
ever actually gets fixed, this would lead to better error 
messages this way. but anyway moving on)



That opDispatch just creates the aliases on-demand. You can't 
reflect over them directly if you wanted to - you'd still have to 
check enum members of Options.StringOption, which means things 
like std.conv.to won't pick it up, but it would work in normal 
use quite beautifully.




If you did want to do the ahead-of-time static foreach way, 
remember, never use .stringof. Find another way.


and tbh i'd ditch the std.traits thing too, it just complicates 
things. Use the language feature allMembers directly and it 
simplifies to this:


```
mixin template StrOptAliases()
{
static foreach(name; __traits(allMembers, StringOption))
mixin("alias " ~ name ~ " = " ~ " __traits(getMember, 
StringOption, name);");

}
```

Notice that the ONLY thing outside the quotes to the mixin is the 
name. Everything else is inside. That's often the solution to 
follow my "never use stringof" advice - just leave things inside 
the quotes. String interpolation / concat is actually very rarely 
needed to build mixins. New declaration names are the main 
exception. But most everything else can just be referenced 
directly and it leads to code that is both less buggy and easier 
to read.


And, of course, it doesn't rely on random underspecified 
.stringof behavior that the compiler can change randomly in any 
release which is just the cherry on top.


Re: Understanding range.dropBackOne

2021-09-28 Thread Adam Ruppe via Digitalmars-d-learn

On Tuesday, 28 September 2021 at 22:56:17 UTC, Tim wrote:

I'm doing the following:

int[25] window = 0;


Note that this array has a fixed size.


window = someInteger ~ window[].dropBackOne;


Here the window[] takes a variable-length slice of it. Turning it 
from int[25] into plain int[]. Then you can drop one since it is 
variable length. Then appending again ok cuz it is variable. Then 
the window assign just copies it out of the newly allocated 
variable back into the static length array.



window = someInteger ~ window.dropBackOne;


But over here you are trying to use the static array directly 
which again has fixed length, so it is impossible to cut an item 
off it or add another to it.


What does the `[]` do exactly? Is an array not a bidirectional 
range?


It takes a slice of the static array - fetching the pointer and 
length into runtime variables.


Re: Templates for instantiating derived class

2021-09-20 Thread Adam Ruppe via Digitalmars-d-learn

On Monday, 20 September 2021 at 22:16:47 UTC, rjkilpatrick wrote:

auto opBinary(string op)(int rhs) const if (op == "+") {
return new Super(_a + rhs); // Creates of type Super 
even when called from derived class

}


Make this

auto opBinary(string op, this This)(int rhs) .
  return new This(_a + rhs);
}


The template this param is the static type it is called on.

https://dlang.org/spec/template.html#template_this_parameter


Note though that this is the static type. If you  do

Super thing = new Derived();
thing + 5;


it will still return Super since that's the type it was called 
through. If you want it to actually return derived, you'll have 
to add a virtual factory function:



class Super {
protected Super factory() { return new Super(); }
}

class Derived : Super {
override Derived factory() { return new Derived(); }
}


Then you can call obj.factory to get the right dynamic type. 
(forward args as needed etc.)


Some kind of `return new this(...)` would be good, but that's 
not possible.


You can do `return new typeof(this)(...);` fyi but it is again 
the static type of this, which will be whatever it is where it is 
defined. This is a useful trick if you were to make that factory 
function a mixin template or something though.


Re: interface function member declarations needing parameter attributes ?

2021-07-17 Thread Adam Ruppe via Digitalmars-d-learn

On Saturday, 17 July 2021 at 20:42:06 UTC, someone wrote:
From the interface perspective: are these signatures identical 
or not ?


No, they are very different.

But you also don't gain much from const here and that ref is 
probably actively harmful so i wouldn't use them here.


Re: function parameters: is it possible to pass byref ... while being optional at the same time ?

2021-07-17 Thread Adam Ruppe via Digitalmars-d-learn

On Saturday, 17 July 2021 at 20:49:58 UTC, someone wrote:

   ref classTickerID robjTickerID


Why are you using ref here at all?

You probably shouldn't be using it. But if it is legitimately 
needed you can do a pointer instead of ref.





Re: UFCS doubt

2021-07-08 Thread Adam Ruppe via Digitalmars-d-learn

On Thursday, 8 July 2021 at 22:24:26 UTC, Antonio wrote:
I supossed  that ```mfp(c,20)``` and ```c.mfp(20)``` should be 
equivalent because UFCS in second example, but it is not... why?


UFCS only works with functions defined at top level, not nested 
inside other functions. That's just how it is defined i don't 
really know why.