Re: How does one attach a manifest file to a D executable on Windows?

2024-06-02 Thread John Chapman via Digitalmars-d-learn

On Sunday, 2 June 2024 at 21:46:41 UTC, solidstate1991 wrote:
Well, it turns out I used the windres found in mingw instead of 
`rc.exe` since the latter cannot be found anywhere on my PC, 
even after reinstalling stuff. I need to hunt it down somehow.


rc.exe comes with the Windows SDK - it gets installed in one of 
the subfolders of "C:\Program Files (x86)\Windows Kits\10\bin" 
(on my machine it's in "10.0.22000.0\x64").


Re: How does one attach a manifest file to a D executable on Windows?

2024-05-25 Thread John Chapman via Digitalmars-d-learn

On Saturday, 25 May 2024 at 13:13:08 UTC, solidstate1991 wrote:

No, I meant something like this:

https://learn.microsoft.com/en-us/windows/win32/controls/cookbook-overview


Not tested but from memory I do this:

1) Copy that first XML snippet from the page you linked, save to 
a file called example.exe.manifest
2) Create a resource script file called resources.rc, with this 
at the top:

   1 24 "example.exe.manifest"
3) Compile it with rc.exe
4) Include the resulting resources.res on your DMD command line

You might also need to call InitCommonControls or 
InitCommonControlsEx before creating any windows.


Re: Getting a total from a user defined variable

2023-04-20 Thread John Chapman via Digitalmars-d-learn

On Thursday, 20 April 2023 at 19:41:21 UTC, Joel wrote:

// how do I get the total of ages added together?


p.map!(x => x.age).sum();


Re: How can a function pointer required to be extern(C)?

2023-04-12 Thread John Chapman via Digitalmars-d-learn

On Wednesday, 12 April 2023 at 20:36:59 UTC, H. S. Teoh wrote:

---snip---
extern(C) void* abc(void*) {return null;}

alias FuncPtr = typeof();


You can also express it like this:

```d
extern(C) alias FuncPtr = void* function(void*);
```


Re: staticMap but with two arguments

2023-02-09 Thread John Chapman via Digitalmars-d-learn

On Thursday, 9 February 2023 at 19:17:55 UTC, Ali Çehreli wrote:
I could not figure out eliminating the hard-coded 4. Can we 
introspect the parameter list of a template like 'fun' in the 
example? If we could, then we could get 4 that way.


Thank you for this. I don't mind hard-coding the N argument. 
TemplateArgsOf needs an instantiated template but maybe ```enum N 
= count(fun.stringof, ',') + 1``` is good enough.


Re: staticMap but with two arguments

2023-02-08 Thread John Chapman via Digitalmars-d-learn

On Monday, 6 February 2023 at 09:17:07 UTC, Ali Çehreli wrote:

I adapted staticMap's implementation to two sets of arguments:


So I've got this implementation, but wonder if I can generalise 
the arg splitting portion rather than write it manually for each 
N?


```d
template staticMapN(size_t N, alias fun, args...) if (args.length 
% N == 0) {

  alias staticMapN = AliasSeq!();
  static foreach (i; 0 .. args.length / N)
static if (N == 1)
  staticMapN = AliasSeq!(staticMapN, fun!(args));
else static if (N == 2)
  staticMapN = AliasSeq!(staticMapN, fun!(args[0 .. $ / 
N][i], args[$ / N .. ($ / N) * 2][i]));

else static if (N == 3)
  staticMapN = AliasSeq!(staticMapN, fun!(args[0 .. $ / 
N][i], args[$ / N .. ($ / N) * 2][i], args[($ / N) * 2 .. ($ / N) 
* 3][i]));

// etc
}
```


Re: staticMap but with two arguments

2023-02-06 Thread John Chapman via Digitalmars-d-learn

On Monday, 6 February 2023 at 09:17:07 UTC, Ali Çehreli wrote:

I adapted staticMap's implementation to two sets of arguments:


Thanks Ali, that's perfect. I thought of splitting the args in 
half a few hours later but hadn't got around to trying it.


staticMap but with two arguments

2023-02-05 Thread John Chapman via Digitalmars-d-learn
I have two AliasSeqs: one containing a function's parameters 
(SourceSeq), the other containing the types I want to convert 
said parameters to (TargetSeq). I'd use something like staticMap 
to call the conversion function with both a parameter from 
SourceSeq and a type from TargetSeq, and return an AliasSeq of 
converted values which will be forwarded to another function. 
staticMap's "fun" can only be instantiated with a single 
argument, while I need it to work with two.


E.g.:
```
template toTarget(alias source, Target) {
  static if (is(typeof(source) == int) && is(Target == string)) 
// for example, convert int to string

}

alias TargetSeq = Parameters!targetFunc;

auto wrapperFunc(A...)(A) {
  alias SourceSeq = __traits(parameters);
  return targetFunc(staticMap!(toTarget, SourceSeq)); // How 
would I call staticMap (or something similar) with SourceSeq 
*and* TargetSeq?

}
```

I could build the list of converted values manually but I wanted 
something smart (like staticMap) to do it inline. I thought 
ApplyLeft/Right could help but couldn't get my head around it.


Re: Mixin helper help

2023-01-14 Thread John Chapman via Digitalmars-d-learn

On Friday, 13 January 2023 at 14:32:44 UTC, Salih Dincer wrote:

Why not directly use the mixin template for opDispatch()?


My opDispatch generates code based on the arguments passed, 
interpolating variable names and functions based on the type. I 
wanted to remove the double braces in my static foreach (needed 
as I declared some aliases inside but since it creates a scope 
those new variables can't be referred to outside of it). I saw 
Adam's post here 
http://dpldocs.info/this-week-in-d/Blog.Posted_2022_12_26.html 
showing use of a "helper" template, and I was trying to adapt it.


I've since just dropped the double braces and removed the 
aliases. It's not as clean but works.


Mixin helper help

2023-01-12 Thread John Chapman via Digitalmars-d-learn

I'm obviously doing something wrong, but don't quite understand.

```d
mixin template helper() {
  mixin("writeln(12);");
}

struct Foo {
  void opDispatch(string name)() {
import std.stdio;
mixin helper!();
//mixin("writeln(12);");
  }
}

void main() {
  Foo.init.opDispatch!"bar"();
}
```

The compiler emits these errors about the mixin ("writeln(12);"):
unexpected `(` in declarator
basic type expected, not `12`
found `12` when expecting `)`
no identifier for declarator `writeln(_error_)`
semicolon expected following function declaration
declaration expected, not `)`

Why does the commented code work but the mixin not? Thanks for 
any pointers.


Re: How to add struct definition?

2022-09-08 Thread John Chapman via Digitalmars-d-learn

On Friday, 9 September 2022 at 00:16:01 UTC, Injeckt wrote:
I need to add this struct definition in my project. But how to 
do that?

This structure:
https://docs.microsoft.com/en-us/windows/win32/api/iptypes/ns-iptypes-ip_adapter_info


It's defined in DRuntime, so you can just import the module like 
this:


import core.sys.windows.iptypes;


Re: winapi, dll

2020-10-15 Thread John Chapman via Digitalmars-d-learn

On Thursday, 15 October 2020 at 20:13:37 UTC, Atmosfear wrote:

On Thursday, 15 October 2020 at 16:32:06 UTC, Imperatorn wrote:

On Thursday, 15 October 2020 at 12:45:42 UTC, Atmosfear wrote:
I didn't find how to call the queryperformancecounter 
function. I tried this. Returns errors, doesn't know what 
BOOL and LARGE_INTEGER are.


import core.sys.windows.windows;
import core.sys.windows.w32api;
import core.sys.windows.winbase;
pragma(lib, "kernel32");
extern (Windows)
{
BOOL QueryPerformanceCounter(LARGE_INTEGER 
*lpPerformanceCount);

}
void main()
{}


It's already defined. Just use QueryPerformanceCounter, (no 
extern).


I'm a newby. Can you show me an example? In which module is it?


Just import core.sys.windows.windows and call the function like 
so:


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

void main() {
  LARGE_INTEGER pc;
  QueryPerformanceCounter();
}
---


Re: I need "windowsx.d" Someone can send It to me?

2020-09-26 Thread John Chapman via Digitalmars-d-learn

On Friday, 25 September 2020 at 15:03:56 UTC, Marcone wrote:
I need windowsx.d but for I don't know the reason is not in 
dmd. Someone that have it can send to me? I don't know convert 
windowsx.h to windowsx.d


windowsx.h is mostly a bunch of macros that forward to functions 
elsewhere in the SDK. Yes, it's handy, but you can get by without 
it in case you don't manage to get it translated to D. Open 
windowsx.h in your editor, find the macro you want to use, look 
across to the right to see what the macro expands to, and use 
that in your code instead.


A lot of the macros that simply cast between HBITMAP, HPALETTE, 
HFONT, HPEN, HGDIOBJ etc are redundant because in D they're all 
just aliases for void*.


Re: Access violation when using IShellFolder2

2020-09-10 Thread John Chapman via Digitalmars-d-learn

On Thursday, 10 September 2020 at 13:30:15 UTC, FreeSlave wrote:
Thanks. I tried this, but VarDateFromStr does not succeed for 
me.


It turns out the shell embeds some control characters in the 
string, specifically 8206 and 8207. So remove those before 
passing it to VarDateFromStr.


auto temp = strRet.pOleStr[0 .. lstrlenW(strRet.pOleStr)]
  .replace(cast(wchar)8206, "")
  .replace(cast(wchar)8207, "");
DATE date;
VarDateFromStr((temp ~ '\0').ptr, LOCALE_USER_DEFAULT, 0, );



Re: Access violation when using IShellFolder2

2020-09-10 Thread John Chapman via Digitalmars-d-learn

On Wednesday, 9 September 2020 at 22:44:50 UTC, FreeSlave wrote:
Btw do you know how to parse a date returned by GetDetailsOf? 
Couldn't find any examples in C++. I actually can see digits 
representing date and time as a part of the string, but I would 
prefer to use some winapi function to translate it into some 
time type instead of manually parsing the result.


You could look at passing the str.pOleStr field in the 
SHELLDETAILS you got from GetDetailsOf to VarDateFromStr. It will 
give you a DATE value that VariantTimeToSystemTime will convert 
to a SYSTEMTIME from which you can get the years, months, days 
etc.


For example:

SHELLDETAILS details;
GetDetailsOf(pidl, 3, );
DATE date;
VarDateFromStr(details.str.pOleStr, LOCALE_USER_DEFAULT, 0, 
);

SYSTEMTIME st;
VariantTimeToSystemTime(date, );
auto year = st.wYear;
auto month = st.wMonth;

You can convert that into a more D-friendly SysTime object using 
SYSTEMTIMEToSysTime from the std.datetime package.


Re: Access violation when using IShellFolder2

2020-09-09 Thread John Chapman via Digitalmars-d-learn

On Tuesday, 8 September 2020 at 22:24:22 UTC, FreeSlave wrote:
However if I change the type of recycleBin variable to 
IShellFolder (not IShellFolder2), the crash does not happen.


Does IShellFolder2 require some special handling?


The issue is caused by druntime's definition of IShellFolder2. To 
fix it temporarily, just redefine it in your module somewhere:


interface IShellFolder2 : IShellFolder {
  HRESULT GetDefaultSearchGUID(GUID*);
  HRESULT EnumSearches(IEnumExtraSearch*);
  HRESULT GetDefaultColumn(DWORD, ULONG*, ULONG*);
  HRESULT GetDefaultColumnState(UINT, SHCOLSTATEF*);
  HRESULT GetDetailsEx(LPCITEMIDLIST, const(SHCOLUMNID)*, 
VARIANT*);

  HRESULT GetDetailsOf(LPCITEMIDLIST, UINT, SHELLDETAILS*);
  HRESULT MapColumnToSCID(UINT, SHCOLUMNID*);
}

IShellFolder2 isn't the only culprit - IShellView2 will need 
fixing too if you intend to use it. There are probably others as 
well.




Re: final switch problem

2020-06-13 Thread John Chapman via Digitalmars-d-learn

On Saturday, 13 June 2020 at 15:33:55 UTC, Boris Carvajal wrote:

On Saturday, 13 June 2020 at 09:02:21 UTC, John Chapman wrote:
Is this a bug or have I made a mistake? This worked a few days 
ago and I haven't changed my setup since then.


https://issues.dlang.org/show_bug.cgi?id=19548

Your code triggers it by using "-debug" option on 
https://run.dlang.io/ using DMD


Hmm, compiling with -release makes it work. Not a huge issue, 
I'll just avoid final switches in debug mode until it's fixed. 
Thanks.


final switch problem

2020-06-13 Thread John Chapman via Digitalmars-d-learn
If I use a final switch and import std.uni (or any other module 
that imports it, such as std.string), I'm getting unresolved 
external symbol errors with DMD 2.092.


This code triggers the issue:

---
module test;

import std.uni;

enum Cheese { cheddar, edam }

void test(Cheese cheese) {
  final switch (cheese) {
  case Cheese.cheddar: break;
  case Cheese.edam: break;
  }
}

void main() {
  test(Cheese.cheddar);
}
---

error LNK2019: unresolved external symbol "pure nothrow @nogc 
@safe void 
core.internal.switch_.__switch_error!().__switch_error(immutable(char)[], ulong)" (_D4core8internal7switch___T14__switch_errorZQrFNaNbNiNfAyamZv) referenced in function _Dmain


If I remove "final" and add a default case, it compiles fine. Is 
this a bug or have I made a mistake? This worked a few days ago 
and I haven't changed my setup since then.


Re: How to get the pointer of "this" ?

2020-05-26 Thread John Chapman via Digitalmars-d-learn

On Tuesday, 26 May 2020 at 13:37:22 UTC, Vinod K Chandran wrote:

On Tuesday, 26 May 2020 at 12:41:20 UTC, John Chapman wrote:

On Monday, 25 May 2020 at 16:26:31 UTC, Vinod K Chandran wrote:

Here is my full code. Please take a look.
https://pastebin.com/av3nrvtT


Change line 124 to:

SetWindowSubclass(this.mHandle, SUBCLASSPROC(), 
UINT_PTR(subClsID), cast(DWORD_PTR)cast(void*)this);


That is, change `` to `cast(void*)this`.


Hi,
Thanks for the reply. That will work like charm but we need to 
change the code in subclassed button's WndProc  like this--

extern(Windows)
private LRESULT btnWndProc(HWND hWnd, UINT message, WPARAM 
wParam, LPARAM lParam, UINT_PTR scID, DWORD_PTR refData) {

try  {

Button thisBtn = cast(Button)cast(void*)refData;
 {
catch (Exception e) {}



Yes, that should work.


Re: How to get the pointer of "this" ?

2020-05-26 Thread John Chapman via Digitalmars-d-learn

On Monday, 25 May 2020 at 16:26:31 UTC, Vinod K Chandran wrote:

Here is my full code. Please take a look.
https://pastebin.com/av3nrvtT


Change line 124 to:

SetWindowSubclass(this.mHandle, SUBCLASSPROC(), 
UINT_PTR(subClsID), cast(DWORD_PTR)cast(void*)this);


That is, change `` to `cast(void*)this`.


Overload function template for rectangular array

2020-05-25 Thread John Chapman via Digitalmars-d-learn
Is it possible to overload a function template for rectangular 
arrays? Is there any way to tell them apart from normal ones?


void foo(T)(T[] a) {}
void foo(T)(T[][] a) {}

auto ra = new int[][](5, 5);
ra.foo(); // matches both

Thanks for any hints.


Re: Easy way to format int in pragma msg ?

2020-05-14 Thread John Chapman via Digitalmars-d-learn

On Thursday, 14 May 2020 at 09:49:15 UTC, wjoe wrote:
Is there an easy way to print an int in hexadecimal, octal or 
binary representation ?


The documentation on pragma(msg, ...) and a quick web search 
didn't provide an answer.


  import std.string;
  pragma(msg, format("%x", 10));

%x = hex
%o = octal
%b = binary


Re: Win32 Api: How create Open/"Save as" Dialog?

2020-01-11 Thread John Chapman via Digitalmars-d-learn

On Saturday, 11 January 2020 at 10:34:34 UTC, Marcone wrote:

This code works, but I can't get file Path. Someone can help me?

import std;
import core.sys.windows.windows;
pragma(lib, "comdlg32");

void main(){
OPENFILENAME ofn;
wchar* szFileName;


You need to supply a buffer, not a pointer:

  wchar[MAX_PATH] szFileName;


(cast(byte*)& ofn)[0 .. ofn.sizeof] = 0;
ofn.lStructSize = ofn.sizeof;
ofn.hwndOwner = null;


The above lines are unnecessary as D structs are automatically 
initialized and lStructSize is already filled in.


ofn.lpstrFilter = "Text Files (*.txt)\0*.txt\0All Files 
(*.*)\0*.*\0";

ofn.lpstrFile = szFileName;


It wants a pointer to your buffer:

  ofn.lpstrFile = szFileName.ptr;


ofn.nMaxFile = MAX_PATH;
ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | 
OFN_HIDEREADONLY;

ofn.lpstrDefExt = "txt";
if(GetOpenFileNameW()){
  writeln(szFileName); // Print null
  writeln(ofn.lpstrFile); // Print null


You'll need to slice the buffer to the right length:

  import core.stdc.wchar_ : wcslen;
  writeln(ofn.lpstrFile[0 .. wcslen(ofn.lpstrFile.ptr)]);


}
}





Re: Release D 2.089.0

2019-11-05 Thread John Chapman via Digitalmars-d-announce

On Wednesday, 6 November 2019 at 01:16:00 UTC, Manu wrote:

On Tue, Nov 5, 2019 at 5:14 PM Manu  wrote:


On Tue, Nov 5, 2019 at 1:20 PM John Chapman via 
Digitalmars-d-announce  
wrote:

>
> On Tuesday, 5 November 2019 at 19:05:10 UTC, Manu wrote:
> > Incidentally, in your sample above there, `a` and `b` are 
> > not shared... why not just write: `cas(, null, b);` ?? 
> > If source data is not shared, you shouldn't cast to shared.

>
> Because casts were needed in 2.088 and earlier and I just 
> updated to 2.089, unaware of the API change. Should I log 
> `null` not working as a bug?


Yes


But I also think you should update your code to not perform the 
casts. Can you confirm that the null works when removing the 
shared casts?


Yes and no - it compiles when removing the casts, but AVs at 
runtime.


Bug filed: https://issues.dlang.org/show_bug.cgi?id=20359


Re: Release D 2.089.0

2019-11-05 Thread John Chapman via Digitalmars-d-announce

On Tuesday, 5 November 2019 at 19:05:10 UTC, Manu wrote:
Incidentally, in your sample above there, `a` and `b` are not 
shared... why not just write: `cas(, null, b);` ?? If source 
data is not shared, you shouldn't cast to shared.


Because casts were needed in 2.088 and earlier and I just updated 
to 2.089, unaware of the API change. Should I log `null` not 
working as a bug?


Re: Release D 2.089.0

2019-11-04 Thread John Chapman via Digitalmars-d-announce

On Tuesday, 5 November 2019 at 07:52:12 UTC, John Chapman wrote:


Sure - this AVs on DMD 2.088 Windows:

import core.atomic;
void main() {
  Object a, b = new Object;
  cas(cast(shared), null, cast(shared)b);
}


Sorry, I meant it AVs 2.089, but works on 2.088.


Re: Release D 2.089.0

2019-11-04 Thread John Chapman via Digitalmars-d-announce

On Tuesday, 5 November 2019 at 06:44:29 UTC, Manu wrote:
On Mon., 4 Nov. 2019, 2:05 am John Chapman via 
Digitalmars-d-announce, < digitalmars-d-announce@puremagic.com> 
wrote:


Something has changed with core.atomic.cas - it used to work 
with `null` as the `ifThis` argument, now it throws an AV. Is 
this intentional?


If I use `cast(shared)null` it doesn't throw but if the change 
was deliberate shouldn't it be mentioned?




Changes were made because there were a lot of problems with 
that module...
but the (reasonably comprehensive) unit tests didn't reveal any 
such
regressions. We also build+test many popular OSS projects via 
buildkite,

and there weren't problems.
Can you show the broken code?


Sure - this AVs on DMD 2.088 Windows:

import core.atomic;
void main() {
  Object a, b = new Object;
  cas(cast(shared), null, cast(shared)b);
}


Re: Release D 2.089.0

2019-11-04 Thread John Chapman via Digitalmars-d-announce

On Sunday, 3 November 2019 at 13:35:36 UTC, Martin Nowak wrote:

Glad to announce D 2.089.0, ♥ to the 44 contributors.

This release comes with corrected extern(C) mangling in mixin 
templates, atomicFetchAdd and atomicFetchSub in core.atomic, 
support for link driver arguments, better support of LDC in 
dub, and plenty of other bug fixes and improvements.


http://dlang.org/download.html
http://dlang.org/changelog/2.089.0.html

-Martin


Something has changed with core.atomic.cas - it used to work with 
`null` as the `ifThis` argument, now it throws an AV. Is this 
intentional?


If I use `cast(shared)null` it doesn't throw but if the change 
was deliberate shouldn't it be mentioned?


Re: ... use of ... is hidden by ...; use alias ... to introduce base class overload set ??

2019-10-21 Thread John Chapman via Digitalmars-d-learn

On Sunday, 20 October 2019 at 21:45:35 UTC, Robert M. Münch wrote:

class myWidget : Observer!message {...}

class FilterSubject : SubjectObject!message {
 Disposable subscribe(myWidget observer){...}
}


I tried to add "alias subscribe = SubjectObject.subscribe;" in 
different places, but that didn't help. Nor do I have any how 
that should help...


This should work:

class FilterSubject : SubjectObject!message {
  alias subscribe = typeof(super).subscribe;
  Disposable subscribe(myWidget observer){...}
}


Re: What is the alternative to the setlocale function of c in D? Thank you.

2019-01-28 Thread John Chapman via Digitalmars-d-learn

On Sunday, 27 January 2019 at 16:23:42 UTC, FrankLike wrote:

On Sunday, 27 January 2019 at 10:44:04 UTC, John Chapman wrote:

On Sunday, 27 January 2019 at 06:14:15 UTC, FrankLike wrote:
On Saturday, 26 January 2019 at 09:33:33 UTC, John Chapman 
wrote:




What has that code got to do with setting the console's 
font? So you need to add more code to accomplish that.


You don't need to set the font to achieve the goal, why not?


This should work:

const(char)[] toCodePage(const(char)[] s, uint codePage = 0) {
  import core.sys.windows.winnls, std.utf;

  foreach (char c; s) {
if (c >= 0x80) {
  auto temp = s.toUTF16z();
  char[] result;
  if ((result.length = WideCharToMultiByte(codePage, 0, 
temp, -1, null, 0, null, null)) != 0)
WideCharToMultiByte(codePage, 0, temp, -1, result.ptr, 
cast(int)result.length, null, null);

  return result;
}
  }
  return s;
}

void main() {
  import core.sys.windows.wincon, std.stdio;

  SetConsoleOutputCP(936); // Simplified Chinese codepage
  writeln("字符".toCodePage(936));
}

Yes.

extern(C) int setlocale(int,char*);

static this()
{
import core.stdc.wchar_;
import core.stdc.stdio;
fwide(core.stdc.stdio.stdout,1);
setlocale(0,cast(char*)"china");
}
///
it's simple than yours,and don't need convert every string,why 
not work after D2.0.78.1?


I've no idea, sorry. A quick scan of D's changelogs between those 
versions doesn't reveal anything relevant. But I wonder how your 
code ever worked - on Windows, calling setlocale with "china" 
returns null, which means it's not a valid locale, so did nothing.


This does the right thing:

  extern(C) int _cwprintf(const(wchar)*, ...);

  void main() {
SetConsoleOutputCP(936);
_cwprintf("字符\n");
  }


Re: What is the alternative to the setlocale function of c in D? Thank you.

2019-01-27 Thread John Chapman via Digitalmars-d-learn

On Sunday, 27 January 2019 at 06:14:15 UTC, FrankLike wrote:
On Saturday, 26 January 2019 at 09:33:33 UTC, John Chapman 
wrote:


What has that code got to do with setting the console's font? 
So you need to add more code to accomplish that.


You don't need to set the font to achieve the goal, why not?


This should work:

const(char)[] toCodePage(const(char)[] s, uint codePage = 0) {
  import core.sys.windows.winnls, std.utf;

  foreach (char c; s) {
if (c >= 0x80) {
  auto temp = s.toUTF16z();
  char[] result;
  if ((result.length = WideCharToMultiByte(codePage, 0, temp, 
-1, null, 0, null, null)) != 0)
WideCharToMultiByte(codePage, 0, temp, -1, result.ptr, 
cast(int)result.length, null, null);

  return result;
}
  }
  return s;
}

void main() {
  import core.sys.windows.wincon, std.stdio;

  SetConsoleOutputCP(936); // Simplified Chinese codepage
  writeln("字符".toCodePage(936));
}


Re: What is the alternative to the setlocale function of c in D? Thank you.

2019-01-26 Thread John Chapman via Digitalmars-d-learn

On Saturday, 26 January 2019 at 06:03:25 UTC, FrankLike wrote:

On Friday, 25 January 2019 at 15:05:50 UTC, John Chapman wrote:

On Friday, 25 January 2019 at 14:23:15 UTC, FrankLike wrote:
I need to set the font by the code now, because I need to do 
the installer, can't let this installer set the properties on 
each computer?


SetCurrentConsoleFontEx perhaps?

https://docs.microsoft.com/en-us/windows/console/setcurrentconsolefontex


That's so much code than next code.

///
extern(C) int setlocale(int,char*);

static this()
{
import core.stdc.wchar_;
import core.stdc.stdio;
fwide(core.stdc.stdio.stdout,1);
setlocale(0,cast(char*)"china");
}
///
But After D2.078.1,it's not work.
Why?
Thank you.


What has that code got to do with setting the console's font? So 
you need to add more code to accomplish that.


Re: What is the alternative to the setlocale function of c in D? Thank you.

2019-01-25 Thread John Chapman via Digitalmars-d-learn

On Friday, 25 January 2019 at 14:23:15 UTC, FrankLike wrote:
I need to set the font by the code now, because I need to do 
the installer, can't let this installer set the properties on 
each computer?


SetCurrentConsoleFontEx perhaps?

https://docs.microsoft.com/en-us/windows/console/setcurrentconsolefontex



Re: How to split strings into AA using phobos

2018-12-11 Thread John Chapman via Digitalmars-d-learn
On Tuesday, 11 December 2018 at 08:20:32 UTC, Arun Chandrasekaran 
wrote:
A typical example would be to split the HTTP query string into 
an AA.


vibe.d has req.queryString, but no convenient wrapper to access 
it as an AA.


http://localhost/hello?name=abc=123

I've got this far.

auto arr = req.queryString.splitter('&').map!(a => 
a.splitter('='));


Thanks


req.queryString[req.queryString.indexOf('?') + 1 .. $]
  .splitter('&')
  .map!(a => a.splitter('='))
  .map!(a => tuple(a.front, a.back))
  .assocArray


Re: ElementType of MapResult is a delegate??

2018-12-08 Thread John Chapman via Digitalmars-d-learn

On Saturday, 8 December 2018 at 13:02:00 UTC, Yuxuan Shui wrote:

This surprised me A LOT:

https://d.godbolt.org/z/82a_GZ

So if I call something.map!().array, I get an array of 
delegates? That makes no sense to me.


But in your example, "(a) =>" returns "{return tmp;}", which is a 
delegate. Just write "(a) => tmp", or invoke the delegate by 
turning it into a call: "{return tmp;}()".


Ambiguous virtual function

2018-12-05 Thread John Chapman via Digitalmars-d-learn

I get an "ambiguous virtual function" error when I compile this:

  interface I {
void fun();
  }

  mixin template F() {
void fun() {}
  }

  class C : I {
mixin F;
mixin F;
  }

But the error doesn't occur with this:

  class C : I {
mixin F;
void fun() {}
  }

Is the compiler giving the non-mixed-in function special 
treatment?


Re: Function signature as string

2018-11-29 Thread John Chapman via Digitalmars-d-learn
On Thursday, 29 November 2018 at 21:31:57 UTC, Neia Neutuladh 
wrote:

On Thu, 29 Nov 2018 21:11:06 +, John Chapman wrote:
Is there any way to get a string representing a function's 
exact signature as declared in the source? I can generate it 
myself using reflection but it might not be 100% verbatim so 
wanted to know if there's anything built in?


   foreach (m; __traits(allMembers, T)) {
 alias member = __traits(getMember, T, m);
 string signature = // Call some function to get "member"'s
signature as a string
   }


typeof().stringof should do it:

void bar(string s, ref Foo!int i) {}
void main()
{
writeln(typeof().stringof);
}

prints: void function(string s, ref Foo!int i)


That does the trick - thanks.


Function signature as string

2018-11-29 Thread John Chapman via Digitalmars-d-learn
Is there any way to get a string representing a function's exact 
signature as declared in the source? I can generate it myself 
using reflection but it might not be 100% verbatim so wanted to 
know if there's anything built in?


  foreach (m; __traits(allMembers, T)) {
alias member = __traits(getMember, T, m);
string signature = // Call some function to get "member"'s 
signature as a string

  }


Re: How to center dlangui Window on screen

2018-11-29 Thread John Chapman via Digitalmars-d-learn
On Thursday, 29 November 2018 at 13:42:28 UTC, greatsam4sure 
wrote:
Which class in dlangui is use to obtain the screen height and 
width?
A Windom of dimension 280 x 445 in dlangui is the same as a 
Windom of 350 x 550 in Javafx and adobe air.


What could be responsible for this wide difference?
A window of 350 x 550 in adobe air is the same as a window of 
350 x 550 in javafx. So why is dlangui window bigger?


Note that I  am using  w x h for my window dimension and I am 
on windows 10


That looks like DPI scaling is in effect: 280 pixels + 125% DPI = 
350.


There's an example of how to get the screen size here (look for 
getScreenDimensions): 
https://github.com/buggins/dlangui/blob/60159c61e27d86012fbf8f205c75d30196fc0e52/src/dlangui/platforms/windows/winapp.d


Re: Making external types available to mixins

2018-11-24 Thread John Chapman via Digitalmars-d-learn

On Friday, 23 November 2018 at 21:49:55 UTC, Kagamin wrote:
Well, just have all factories in one module and import it, then 
they will be visible.


They're part of another library over which I have no control, but 
yes, I could still import them all and make life easier.



import allfactories;
auto makeWith(string className, Args…)(auto ref Args args) {
  mixin("return makeWith!(I", className, "Factory)(args);"); // 
Fowarded to implementation of makeWith below

}

Or predeclare make functions in factory modules

interface ICalendarFactory
{
  ...
}

alias makeCalendar=makeWith!ICalendarFactory;





Re: memoize & __traits(compiles...)

2018-11-23 Thread John Chapman via Digitalmars-d-learn
On Friday, 23 November 2018 at 11:29:24 UTC, Nicholas Wilson 
wrote:
No, std.functional.memoize uses a hashtable to cache the 
runtime results of calls to expensive functions.


assuming that the example is not oversimplified and 
generateFunc1 and generateFunc2 are functions, the compiler 
doesn't do extra semantic analysis so the validity of the 
functions is effectively cached.


If they are templates (with parameters) then the compiler will 
automatically memoize them (it too keeps a hashtable of 
template instances).


Ah, that's good to know.


memoize & __traits(compiles...)

2018-11-23 Thread John Chapman via Digitalmars-d-learn
I'm doing a fair amount of repeatedly checking if a function 
compiles with __traits(compiles...), executing the function if 
so, erroring out if not, like this:


  static if (__traits(compiles, generateFunc1())) {
return generateFunc1();
  } static if (__traits(compiles, generateFunc2())) {
return generateFunc2();
  } else static assert(false);

But it seems inefficient to have to evaluate those functions 
twice, so I'd like to optimise this so if __traits(compiles...) 
succeeds, the result is cached and then used when the function is 
actually called. I wondered if using std.functional.memoize would 
help?


Re: Making external types available to mixins

2018-11-23 Thread John Chapman via Digitalmars-d-learn
On Thursday, 22 November 2018 at 16:27:08 UTC, Eduard Staniloiu 
wrote:

So I had a go at this and I have a working solution.
https://run.dlang.io/is/oaH6Ib

At first, I tried to do everything in the mixin, as you can see 
with the `failedAttempt` function. The idea was that this 
should have worked like `mixin(failedAttempt!"Calendar"(1, 2, 
3));`. As you can see, and the name suggests, I wasn't able to 
make it work with `args`.


The solution I have to your problem is to use a template, in 
this case the `theType` template that will expand to the fully 
qualified name. So you'd use it like

`makeWith!(theType!"Calendar")(args);`

Hope it helps!

Edi


Thanks!


Re: task can't take a class method

2018-11-19 Thread John Chapman via Digitalmars-d-learn

On Monday, 19 November 2018 at 16:29:01 UTC, helxi wrote:

On Monday, 19 November 2018 at 16:10:15 UTC, helxi wrote:

...


Oh wait never mind I was missing a bracket:

auto proc = task!(ddCall.dd());

Now I have another thing to worry about: ddcall.dd() cannot be 
read at compile time.


You're attempting to execute "dd" at compile time. You should be 
able to pass the function to a task in a couple of ways:


1) task()
2) task!(ddCall.dd)



Re: Making external types available to mixins

2018-11-18 Thread John Chapman via Digitalmars-d-learn
On Saturday, 17 November 2018 at 21:11:38 UTC, Adam D. Ruppe 
wrote:
On Saturday, 17 November 2018 at 17:58:54 UTC, John Chapman 
wrote:

Has anyone had a similar need and come up with a solution?


You might be able to just pass it the Calendar type, and then 
fetch its parent module and get the ICalendarFactory from there 
(assuming they are defined in the same module).


But generally speaking, passing strings to a mixin that refer 
to something in another module isn't going to work well thanks 
to scoping rules. You are better off passing a symbol of some 
sort.


So there is no actual Calendar type. There's an ICalendarFactory 
type that creates instances of ICalendar (these types are part of 
a third-party API).  "Calendar" is just a key users could use 
when calling a "makeWith" method that would build the 
ICalendar/Factory names, instantiate the factory, call the 
appropriate factory method and return the result. There are 
thousands of such object/factory pairs in the API. Just trying to 
cut out a lot of boilerplate code, but it doesn't seem doable 
this way.


Making external types available to mixins

2018-11-17 Thread John Chapman via Digitalmars-d-learn
The following code doesn't compile because the generated type 
name needs to be available inside the mixin's scope, whereas it's 
actually in another module.


auto makeWith(string className, Args…)(auto ref Args args) {
  mixin("return makeWith!(I", className, "Factory)(args);"); // 
Fowarded to implementation of makeWith below

}

auto makeWith(T, Args…)(auto ref Args args) … // This is the 
implementation


The idea is that users could type (for example) 
makeWith!`Calendar`(…) instead of the longer 
makeWith!ICalendarFactory(…).


I tried mixing in an import statement with the help of 
std.traits.moduleName so that the I...Factory type would be 
available but again the compiler complains that it's undefined.


Has anyone had a similar need and come up with a solution?


Re: Profiling DMD's Compilation Time with dmdprof

2018-11-08 Thread John Chapman via Digitalmars-d-announce
On Thursday, 8 November 2018 at 20:19:47 UTC, Vladimir Panteleev 
wrote:
On Thursday, 8 November 2018 at 19:07:32 UTC, Jacob Carlborg 
wrote:
21 seconds on a Windows 10 virtual machine compiling using the 
win32.mak file.


Sounds like we're narrowing it down to the Visual Studio 
solution.


Well, I'm just using win32.mak in a command prompt and it takes 
~1m 40s to build DMD. It just seems to do nothing for most of 
that time.


Re: Accessing LPARAM param from SendMessage acts weird.

2018-11-04 Thread John Chapman via Digitalmars-d-learn

On Sunday, 4 November 2018 at 19:06:22 UTC, Mark Moorhen wrote:

Another Windows challenge:

I'm trying to get the title of the active window even if it is 
from an external application. This is what I've come up with so 
far:



import std.stdio;
import core.sys.windows.windows;

extern (Windows)

void main()
{
HWND foreground = GetForegroundWindow();
const(wchar) title;

int length = SendMessage(foreground, WM_GETTEXTLENGTH, 0, 0);
	SendMessage(foreground, WM_GETTEXT, length, 
LPARAM(title));			//LPARAM is a Long Pointer


writeln(length);
writeln(title);

}


Outputs :

27
  ´┐┐

So the lengt of the foreground windows title should be 27 chars 
long, but the title is only 3 chars (and kinda funny ones too:-(


Anyone ideas?


You need to allocate some memory to receive the string from 
WM_GETTEXT.


  auto length = SendMessage(foreground, WM_GETTEXTLENGTH, 0, 0);
  auto buffer = new wchar[length + 1]; // +1 for the trailing 
null character
  SendMessage(foreground, WM_GETTEXT, buffer.length, 
cast(LPARAM)buffer.ptr);

  auto title = cast(wstring)buffer[0 .. length];
  writeln(title);


Re: Private struct constructor

2018-10-04 Thread John Chapman via Digitalmars-d-learn

On Thursday, 4 October 2018 at 07:31:21 UTC, Ritchie wrote:

Any reason why this works?

https://run.dlang.io/is/TALlyw


"private" applies to the module, not the type. 
https://dlang.org/spec/attribute.html#visibility_attributes


Re: Use nested functions as callbacks with Windows API functions?

2018-10-02 Thread John Chapman via Digitalmars-d-learn

On Monday, 1 October 2018 at 20:27:43 UTC, spikespaz wrote:
Of course there is nothing wrong with defining each callback as 
a separate function, but then comes the issue of naming them. I 
also don't like the way it makes my code look.


I think the best you can do is something like this:

---
auto callback(T, string file = __FILE__, size_t line = 
__LINE__)(T handler) {

  import std.traits;

  __gshared T handler_;
  handler_ = handler;

  extern(Windows)
  ReturnType!T fn(Parameters!T args) {
synchronized return handler_(args);
  }

  return 
}

void main() {
  HWND[] list;
  EnumWindows((HWND hwnd, LPARAM lparam) {
list ~= hwnd;
return TRUE;
  }.callback(), 0);
  writeln(list);
}
---



Re: Convert output range to input range

2018-03-17 Thread John Chapman via Digitalmars-d-learn

On Saturday, 17 March 2018 at 17:16:40 UTC, David Nadlinger wrote:

On Friday, 16 March 2018 at 07:57:04 UTC, John Chapman wrote:
I need to write to a range created with outputRangeObject, 
then read from it. Is there a way to convert it to an input 
range?


Could you illustrate your problem a bit further?


I'm trying to replace the old std.streams in my app with ranges. 
I'm interfacing with a networking library to which I supply a 
callback that when invoked provides the requested data. I write 
that data to an output range, but later on I need to read that 
data from the range too - which of course you can't do.


So what I'm looking for is the range-based equivalent of a 
MemoryStream.




Convert output range to input range

2018-03-16 Thread John Chapman via Digitalmars-d-learn
I need to write to a range created with outputRangeObject, then 
read from it. Is there a way to convert it to an input range?


Re: How to proceed with learning to code Windows desktop applications?

2018-01-31 Thread John Chapman via Digitalmars-d-learn

On Wednesday, 31 January 2018 at 11:52:20 UTC, rumbu wrote:
On Windows platform, WPF is the way to go right now. Once you 
accommodate yourself with XAML (descriptive language for 
designing windows and controls), you can step up from WPF to 
modern Windows apps (UWP). Unfortunately, none of these 
technologies are supported in D.


Just to say that it is actually possible to write modern Windows 
apps in D - I've done it. WinRT is just COM. Granted it's not as 
easy as using Microsoft's language projections, but it's doable 
if you really want to.


Re: Get aliased type

2018-01-02 Thread John Chapman via Digitalmars-d-learn

On Tuesday, 2 January 2018 at 12:19:19 UTC, David Nadlinger wrote:
There is indeed no way to do this; as you say, aliases are just 
names for a particular reference to a symbol. Perhaps you don't 
actually need the names in your use case, though?


 — David


The idea was to distinguish between a BSTR (an alias for wchar* 
from core.sys.windows.wtypes used widely with COM) and wchar* 
itself, chiefly so that I could call the appropriate Windows SDK 
functions on them to convert them to and from D strings. Although 
BSTRs look like wchar*s to the end user they are not really 
interchangable - for example, calling SysFreeString on a regular 
wchar* will cause a crash.


According to the docs, a BSTR is prefixed with its length and 
ends in a null character, but I'm not sure if checking for the 
existence of those is going to be good enough.


Get aliased type

2018-01-02 Thread John Chapman via Digitalmars-d-learn
Because an alias of a type is just another name for the same 
thing you can't test if they're different. I wondered if there 
was a way to get the aliased name, perhaps via traits? (.stringof 
returns the original type.)


I can't use Typedef because I'm inspecting types from sources I 
don't control.


Re: std.file and non-English filename in Windows

2018-01-01 Thread John Chapman via Digitalmars-d-learn

On Sunday, 31 December 2017 at 18:21:29 UTC, Domain wrote:
In Windows, exists, rename, copy will report file not exists 
when you input non-English filename, such as Chinese 中文.txt


Works for me. I created a file with the name "中文.txt" and 
std.file.exists returned true.


Is your D source file saved in ASCII by any chance? Try saving it 
with a different encoding, such as UTF8.


Re: Calling a d-style-variadic-function from another

2017-12-30 Thread John Chapman via Digitalmars-d-learn

On Saturday, 30 December 2017 at 10:14:35 UTC, tipdbmp wrote:


// how can I adjust _argptr?
_argptr = ???


Try this:
  _argptr = *cast(va_list*)_argptr;



Re: Embedded Containers

2017-12-05 Thread John Chapman via Digitalmars-d
On Tuesday, 5 December 2017 at 19:01:48 UTC, A Guy With a 
Question wrote:

The following doesn't appear to be valid syntax. Array!Item!T

I get the following error:

"multiple ! arguments are not allowed"

Which is ok...I get THAT error, however, this does not work 
either:


alias Items(T) = Array!Item(T);

This gives me the error:

Error: function declaration without return type. (Note that 
constructors are always named `this`)	


Your wrapping the wrong part in parentheses.

  Array!(Item!T)

It would actually be Array!(Item!(T)), but if a single type is 
specified you're allowed to omit the parentheses when 
instantiating.




Item is defined as follows:

interface Item(T)
{
   @property
   T member();
}

That part compiles fine. However, even when I remove the 
aliasing, I can't import this interface. I get "Error: 
undefined identifier 'Item'"


I'm not quite sure I understand how to create a generic 
container interface or class in D. Half of how I expect it to 
work works, but the other half doesn't. The docs aren't too 
helpful. I'm not sure if it's a case where there's just too 
much to go through or if what I'm trying to do isn't really 
covered. Essentially I'm trying to create an array of this type 
'Item' that has some generic members. I think people who come 
from C# will kind of get what I'm trying to do here, because 
I'm trying to port C# code.


What other problems are you having? I did the same and it was 
fairly straightforward.




Re: Is variable void?

2017-11-25 Thread John Chapman via Digitalmars-d-learn
On Saturday, 25 November 2017 at 15:38:15 UTC, Adam D. Ruppe 
wrote:
nope. It'd be indistinguishable from the user just happening to 
initialize it to some random value.


Thanks. I'll got with .init instead.



Is variable void?

2017-11-25 Thread John Chapman via Digitalmars-d-learn
Is there any way of determining whether a variable has been 
initialized or not? For example, if something is declared like 
this:


  int x = void;

can I check if it's void before I use it, say, in a function it's 
been passed to?




Re: Whats the correct way to pass a D array type to a win32 api function wanting a buffer?

2017-07-13 Thread John Chapman via Digitalmars-d-learn

On Thursday, 13 July 2017 at 01:15:46 UTC, FoxyBrown wrote:

ENUM_SERVICE_STATUS_PROCESS[5000] services;
	auto res = SVC.EnumServicesStatusExA(schSCManager, 
SC_ENUM_TYPE.SC_ENUM_PROCESS_INFO, servicesType, 
SERVICE_STATE_ALL, cast(ubyte*)services.ptr, 
5000*ENUM_SERVICE_STATUS_PROCESS.sizeof, , 
, , cast(const(char)*)null);


You need to call EnumServicesStatusEx twice - the first time to 
get the required size of the buffer. See the docs for the 
lpServices parameter here 
https://msdn.microsoft.com/en-us/library/windows/desktop/ms682640(v=vs.85).aspx


Then allocate a buffer using the returned dwBytesNeeded and call 
the function again with your buffer and its size.


Re: DMD VS2017 Support

2017-04-30 Thread John Chapman via Digitalmars-d

On Sunday, 30 April 2017 at 16:05:10 UTC, Igor wrote:

On Sunday, 30 April 2017 at 15:53:07 UTC, Mike Parker wrote:

On Sunday, 30 April 2017 at 14:56:44 UTC, Igor wrote:



I tried updating sc.ini to new paths but I still get this 
error. Can someone offer some advice?


Which paths did you set?


These are the ones I changed:

VCINSTALLDIR=C:\Program Files (x86)\Microsoft Visual 
Studio\2017\Community\VC\Tools\MSVC\14.10.25017\

UCRTVersion=10.0.15063.0

LINKCMD=%VCINSTALLDIR%\bin\HostX64\x64\link.exe

PATH=%PATH%;%VCINSTALLDIR%\bin\HostX64\x64

LIB=%LIB%;"%VCINSTALLDIR%\lib\x64"

Same for x86 environment, except, of course I replaced x64 with 
x86 in the values.


I should also mention that compiling using DUB works. It only 
doesn't work from VS.


Here are mine, if it helps:

VCINSTALLDIR=C:\Program Files (x86)\Microsoft Visual 
Studio\2017\Community\VC

WindowsSdkDir=C:\Program Files (x86)\Windows Kits\10
UniversalCRTSdkDir=C:\Program Files (x86)\Windows Kits\10
UCRTVersion=10.0.15063.0
LINKCMD=%VCINSTALLDIR%\Tools\MSVC\14.10.25017\bin\HostX64\x64\link.exe
PATH=%PATH%;%VCINSTALLDIR%\Tools\MSVC\14.10.25017\bin\HostX64\x64
LIB=%LIB%;"%VCINSTALLDIR%\Tools\MSVC\14.10.25017\lib\x64"
LIB=%LIB%;"%UniversalCRTSdkDir%\Lib\%UCRTVersion%\um\x64"
LIB=%LIB%;"%UniversalCRTSdkDir%\Lib\%UCRTVersion%\ucrt\x64"



Re: COM Expertise needed: COM Callbacks

2017-04-28 Thread John Chapman via Digitalmars-d-learn

On Thursday, 27 April 2017 at 20:20:23 UTC, Nierjerson wrote:


I think the main issue though, is that I really don't know what 
is going on when I invoke the PS function. It seems to call the 
server method that takes the interface and then the server does 
it's "magic"(which is calling my QueryInterface) but how the 
implemented QueryInterface is suppose to respond is beyond 
me... I've tried some based stuff but nothing seem to work. The 
good news is that it is doing something(calling QueryInterface) 
which means that the server is at work.


Any more ideas?  I think the issue currently is is the 
QueryInterface(it is simply not doing what it is suppose to). 
I'll probably have to look at some other implementations to see 
what is going on.


QueryInterface is COM's version of opCast. It asks if you support 
the interface represented by an IID (riid). If you don't, then 
you return E_NOINTERFACE. If you do, then you point the result 
(pvObject) to yourself and return S_OK. Here's a basic 
implementation:


extern(Windows)
HRESULT QueryInterface(IID* riid, void** pvObject) {
  if (pvObject is null) return E_POINTER;
  *pvObject = null;

  if (*riid == IID_IUnknown) *pvObject = 
cast(void*)cast(IUnknown)this;
  else if (*riid == IID_IDispatch) *pvObject = 
cast(void*)cast(IDispatch)this;

  // and so on for all interfaces we support

  if (*pvObject is null) return E_NOINTERFACE;
  (cast(IUnknown)this).AddRef();
  return S_OK;
}

AddRef/Release perform the COM object's reference counting, so 
you should implement them too.


However, I don't understand why your icRBCColor class both 
implements and encapsulates IDispatch - the generated version 
cRGBColor from Gen.d just encapsulates it. Why do you need to 
instantiate an instance of icRGBColor? Can't you just use the 
rgb1 object you got from the dd.RGB() getter, assign the colour 
values to its Red, Blue, Green properties as needed, then call 
the dd.RGB(rgb1) setter? Does that not work?


Re: COM Expertise needed: COM Callbacks

2017-04-27 Thread John Chapman via Digitalmars-d-learn

On Wednesday, 26 April 2017 at 23:04:53 UTC, Nierjerson wrote:

On Wednesday, 26 April 2017 at 15:30:37 UTC, John Chapman wrote:

On Tuesday, 25 April 2017 at 18:39:56 UTC, Nierjerson wrote:

[...]


When you use DISPATCH_PROPERTYPUT you need to set cNamedArgs 
and rgdispidNamedArgs like so:


  int dispidNamed = DISPID_PROPERTYPUT;
  params.cNamedArgs = 1;
  params.rgdispidNamedArgs = 

You should also call AddRef on any COM objects you add to your 
paramVars array.



Did you try this? I tried and same issue. Are you sure the 
above is required? I'm not using any "named" args so not sure 
why it should matter?


From the documentation 
(https://msdn.microsoft.com/en-us/library/windows/desktop/ms221479(v=vs.85).aspx):


"When you use IDispatch::Invoke() with DISPATCH_PROPERTYPUT or 
DISPATCH_PROPERTYPUTREF, you have to specially initialize the 
cNamedArgs and rgdispidNamedArgs elements of your DISPPARAMS 
structure"


Thought it might help.



Re: COM Expertise needed: COM Callbacks

2017-04-26 Thread John Chapman via Digitalmars-d-learn

On Tuesday, 25 April 2017 at 18:39:56 UTC, Nierjerson wrote:

void RGB(icRGBColor ic, cSolidColor s)
{
import main;
EXCEPINFO exception;
uint argErr = 0;
auto iidNULL = IID_NULL;
auto RT = new SafeVariantPtr();
VARIANT[1] paramVars;
	DISPPARAMS params = {rgvarg: paramVars.ptr, cArgs: 1, 
cNamedArgs: 0};

auto ID = s.COMMethodIDs[`RGB`];
	paramVars[0].punkVal = ic; paramVars[0].vt = 
VARENUM.VT_DISPATCH; scope(exit) VariantClear([0]);
	auto res = s.iDispatch.Invoke(cast(int)ID, , 0, 
DISPATCH_PROPERTYPUT, , cast(VARIANT*)RT, , 
);
	assert(res == S_OK, `Could not invoke COM Function 
cSolidColor.RGB. Error `~to!string(res, 16));


}


When you use DISPATCH_PROPERTYPUT you need to set cNamedArgs and 
rgdispidNamedArgs like so:


  int dispidNamed = DISPID_PROPERTYPUT;
  params.cNamedArgs = 1;
  params.rgdispidNamedArgs = 

You should also call AddRef on any COM objects you add to your 
paramVars array.


Re: opDispatch/template get this

2017-04-04 Thread John Chapman via Digitalmars-d-learn

On Monday, 3 April 2017 at 21:49:07 UTC, Inquie wrote:

I am using opDispatch to wrap function calls

Error: 'this' is only defined in non-static member functions, 
not opDispatch!"foo"


class X
{
auto localfoo() { return 3; }
template opDispatch(string name, Args...)
{
static if (name == `foo`) { alias opDispatch = () { 
return this.localfoo();

};
}


which doesn't work because of this

I tried

template opDispatch(string name, this _this, Args...)
{
	static if (name == `foo`) { alias opDispatch = () { return 
_this.localfoo(); };

}

but that doesn't work either ;/

I call it like

auto y = x.foo();

but foo isn't found


https://dpaste.dzfl.pl/bf31f535340f



class X
{
auto localfoo() { return 3; }
auto localfoo2(int x) { return x; }
template opDispatch(string name, Args...)
{
static if (name == `foo`)
{
alias opDispatch = () { return this.localfoo(); };
}
static if (name == `bar`)
{
			alias opDispatch = () { return this.localfoo2(); }; // need 
to be able to pass Args properly here

}
}
}

void main()
{
auto x = new X();
auto z = x.localfoo();
auto y = x.foo();
auto q = x.bar();
}


Make opDispatch a templated function and forward with 
__traits(getMember, this, "foo") or a mixin.


class X {

  auto localfoo() { return 3; }
  auto localfoo2(int x) { return x; }

  auto opDispatch(string name, Args...)(auto ref Args args) {
static if (name == "foo") return __traits(getMember, this, 
"localfoo")(args);
else static if (name == "bar") mixin("return 
localfoo2(args);");

  }

}


Re: COM2D Wrapper

2017-03-28 Thread John Chapman via Digitalmars-d-learn

On Monday, 27 March 2017 at 21:02:05 UTC, Nierjerson wrote:
Anyone can help get this working? I think the issue maybe that 
the interface pointer returned by the COM interface is "C-like" 
and doesn't match what D expects an interface to be. I get 
access violations when trying to call the functions on the 
returned interfaces. Not sure about this though.


I don't have Photoshop so I can't verify this, however I think 
Photoshop only declares dispinterfaces, meaning those methods 
aren't present in the vtable, so every method will have to be 
called using IDispatch.Invoke.


(I'm guessing IDL2D doesn't distinguish between dual and disp- 
interfaces and just emits any functions it sees.)


Re: Working Windows GUI library - no console Window

2015-11-06 Thread John Chapman via Digitalmars-d-learn

On Friday, 6 November 2015 at 15:52:10 UTC, johann wrote:

hi,
i like to use a window gui library and i think i found a 
working one.


https://github.com/FrankLIKE/dfl2  - works with x64

the problem is, that with DMD 2.069.0, VS2015 and visualD the 
trick of using "-L/SUBSYSTEM:windows,6.00 
-L/ENTRY:mainCRTStartup" does not suppress the console window 
anymore.


does anybody have a solution for that problem?
is anybody still working on that library?

johann


Same problem here. I had to remove the mainCRTStartup flag and 
use WinMain as my entry point.


Re: DMD on WIndows 10

2015-08-01 Thread John Chapman via Digitalmars-d

On Friday, 31 July 2015 at 22:02:13 UTC, Paul D Anderson wrote:
I'm waiting to upgrade from Windows 7 to Windows 10 to avoid 
the inevitable just-released bugs, but does anyone have any 
info about D on Windows 10? Has anyone tried it?


I'm on Windows 10, and my DMD-built programs run just fine.


Re: how to iterate on Array?

2015-06-27 Thread John Chapman via Digitalmars-d-learn

On Saturday, 27 June 2015 at 17:43:13 UTC, aki wrote:

I want to print the contents of Array!int

import std.stdio;
import std.container;

void pr(Array!int a) {
foreach(i, v; a[]) {
writeln(%4s: %s\n, i, v);
}
}

But when I compile it by DMD 2.062 on Windows
it says:

testArray.d(5): Error: cannot infer argument types
(line 5 is at foreach(i, v; a[]) { )

What's wrong? how can I iterate the array?

Thanks, aki.


size_t i;
foreach (v; a[])
  writeln(%s: %s, i++, v);


Re: New names - 2.068 roundup

2015-06-24 Thread John Chapman via Digitalmars-d

On Wednesday, 24 June 2015 at 01:04:01 UTC, Adam D. Ruppe wrote:

The code breakage is minimal


Won't this break isSomeString? Phobos uses this everywhere.


Re: Naming things

2015-06-22 Thread John Chapman via Digitalmars-d

On Monday, 22 June 2015 at 11:45:31 UTC, Wyatt wrote:
 None of the suggestions I've seen so far really call out to me 
hey, this is lazy and has a non-lazy counterpart.  Would it 
be so wrong to add lazy to the beginning or end so it's super 
obvious at a glance with zero cognitive overhead?


-Wyatt


This would be my preferred option. When C# introduced 
asynchronous counterparts of existing methods, they appended 
Async to the names, which seems to have worked out well - eg, 
Wait/WaitAsync, Read/ReadAsync. So we'd have 
setExtension/setExtensionLazy etc.


Re: Can't call GetWindowTextW - Error:undefined identifier

2015-06-17 Thread John Chapman via Digitalmars-d-learn

On Wednesday, 17 June 2015 at 20:50:27 UTC, John Chapman wrote:

  wchar[MAX_PATH] buffer;
  int length = GetWindowTextW(GetForegroundWindow(), 
buffer.ptr, buffer.length);


Don't know why I used MAX_PATH there. You should probably 
dynamically allocate a buffer based on GetWindowTextLengthW.


  extern(Windows)
  int GetWindowTextLengthW(HWND hWnd);

Putting it all together:

  import core.stdc.stdlib : malloc, free;
  import std.utf;

  HWND hwnd = GetForegroundWindow();
  int length = GetWindowTextLengthW(hwnd);
  if (length  0) {
auto buffer = cast(wchar*)malloc((length + 1) * wchar.sizeof);
scope(exit) free(buffer);

length = GetWindowTextW(hwnd, buffer, length);
if (length  0)
  auto title = buffer[0 .. length].toUTF8();
  }


Re: Can't call GetWindowTextW - Error:undefined identifier

2015-06-17 Thread John Chapman via Digitalmars-d-learn

On Wednesday, 17 June 2015 at 21:00:55 UTC, Dan wrote:

thank you John it worked :)

do I always need do the same for all windows API?


For most Win32 API functions, yes. Although there are some more 
complete headers on Github (for example, 
https://github.com/rikkimax/WindowsAPI).


Re: Can't call GetWindowTextW - Error:undefined identifier

2015-06-17 Thread John Chapman via Digitalmars-d-learn

On Wednesday, 17 June 2015 at 20:40:02 UTC, Dan wrote:

I'm new to Dlang and I have no Idea whats wrong with this code!

wchar[260] buffer;
HWND hWindow = GetForegroundWindow();
GetWindowTextW(hWindow, buffer, sizeof(title)); -- Problem here


The compiler is complaining it can't find an identifier named 
GetWindowTextW, so you'll have to declare it yourself.


Try this:

  extern(Windows)
  int GetWindowTextW(HWND hWnd, LPWSTR lpString, int nMaxCount);

And call it like so:

  wchar[MAX_PATH] buffer;
  int length = GetWindowTextW(GetForegroundWindow(), buffer.ptr, 
buffer.length);


Re: Calling a cpp function from d

2015-06-17 Thread John Chapman via Digitalmars-d-learn

On Tuesday, 16 June 2015 at 12:42:16 UTC, C2D wrote:

On Tuesday, 16 June 2015 at 12:31:23 UTC, John Chapman wrote:

On Tuesday, 16 June 2015 at 12:26:45 UTC, C2D wrote:

BOOL result = SHGetFolderPath(null, 0x23, null, 0, cache.ptr);


That should be:

BOOL result = SHGetFolderPath(null, 0x23, null, 0, buf.ptr);


Thanks, but I'm still getting the same error -


Use SHGetFolderPathW.


Re: Calling a cpp function from d

2015-06-17 Thread John Chapman via Digitalmars-d-learn

On Tuesday, 16 June 2015 at 12:42:16 UTC, C2D wrote:

On Tuesday, 16 June 2015 at 12:31:23 UTC, John Chapman wrote:

On Tuesday, 16 June 2015 at 12:26:45 UTC, C2D wrote:

BOOL result = SHGetFolderPath(null, 0x23, null, 0, cache.ptr);


That should be:

BOOL result = SHGetFolderPath(null, 0x23, null, 0, buf.ptr);


Thanks, but I'm still getting the same error -


Here's a working version:

import core.sys.windows.windows;

extern(Windows)
HRESULT SHGetFolderPathW(HWND hwndOwner, int nFolder, HANDLE 
hToken, DWORD dwFlags, LPWSTR pszPath);


string getFolderPath(int folder) {
  import core.stdc.wchar_ : wcslen;
  import std.utf : toUTF8;

  wchar[MAX_PATH] buffer;
  if (SHGetFolderPathW(null, folder, null, 0, buffer.ptr) = 0)
return buffer[0 .. wcslen(buffer.ptr)].toUTF8();
  return null;
}

void main() {
  writeln(getFolderPath(0x23));
}


Re: Calling a cpp function from d

2015-06-16 Thread John Chapman via Digitalmars-d-learn

On Tuesday, 16 June 2015 at 12:26:45 UTC, C2D wrote:

BOOL result = SHGetFolderPath(null, 0x23, null, 0, cache.ptr);


That should be:

BOOL result = SHGetFolderPath(null, 0x23, null, 0, buf.ptr);


Re: DIP80: phobos additions

2015-06-10 Thread John Chapman via Digitalmars-d
On Wednesday, 10 June 2015 at 09:30:37 UTC, Robert burner Schadek 
wrote:

On Wednesday, 10 June 2015 at 09:12:17 UTC, John Chapman wrote:


Logging


std.experimental.logger!?


Perfect, he said sheepishly.


Re: DIP80: phobos additions

2015-06-10 Thread John Chapman via Digitalmars-d
It's a shame ucent/cent never got implemented. But couldn't they 
be added to Phobos? I often need a 128-bit type with better 
precision than float and double.


Re: DIP80: phobos additions

2015-06-10 Thread John Chapman via Digitalmars-d

On Wednesday, 10 June 2015 at 07:56:46 UTC, John Chapman wrote:
It's a shame ucent/cent never got implemented. But couldn't 
they be added to Phobos? I often need a 128-bit type with 
better precision than float and double.


Other things I often have a need for:

Weak references
Queues, stacks, sets
Logging
Custom date/time formatting
Locale-aware number/currency formatting
HMAC (for OAuth)
URI parsing
Sending email (SMTP)
Continuations for std.parallelism.Task
Database connectivity (sounds like this is on the cards)
HTTP listener


Re: core.thread.[Ss]leep - Is this a bug?

2015-05-13 Thread John Chapman via Digitalmars-d

On Wednesday, 13 May 2015 at 20:09:44 UTC, wobbles wrote:

On windows,
core.thread.Sleep  (big 'S')

On linux
core.thread.sleep  (little 'S')


I'm trying to import as little symbols as possible, so was 
importing specific items like

import core.thread : Sleep;

but it fails when I compile on linux, so I need to do a
version(Windows) import core.thread : Sleep;
version(Posix) import core.thread : sleep;

Seems like a bug?


No, you should be calling Thread.sleep (capital T) instead.


Re: windows wininet library

2015-02-01 Thread John Chapman via Digitalmars-d-learn

On Sunday, 1 February 2015 at 08:37:23 UTC, ketmar wrote:


seems that my idea of using D to write a simple windows utility 
was very
wrong. ok, another attempt to use D for our windows 
developement has
failed. i'm in no way can sell manual .def creation to our 
team -- they
will make fun of me, showing how their Visual C can compile 
this code

without any troubles and external utilities...


It's easier to run coffimplib on the lib files from the Windows 
SDK.


DMD compiler platform documentation AWOL

2015-01-25 Thread John Chapman via Digitalmars-d
Looks like the documentation for DMD's command line switches and 
platform-specific information has disappeared from the site. It 
used to live under Downloads  Tools in menus labelled Linux 
notes, Windows notes etc.


Re: sign oauth request

2014-09-25 Thread John Chapman via Digitalmars-d-learn
there is no HMAC-SHA1 algorithm in phobos library... should I 
implement it from scratch?


http://dlang.org/phobos/std_digest_sha.html#SHA1


Re: John Chapman (Juno), calling for John Chapman (not spam)

2014-06-16 Thread John Chapman via Digitalmars-d-announce

On Thursday, 12 June 2014 at 05:39:06 UTC, Karen Bantoft wrote:
I'm looking for the John Chapman who worked as a programmer at 
Centre-file Ltd, in Finsbury Circus London in 1971.


Any leads?

Karen


Not me, sorry.


Thread name conflict

2014-05-05 Thread John Chapman via Digitalmars-d
Importing both core.thread and std.regex results in a conflict as 
both define a Thread type.


Perhaps the regex module's author assumed there'd be no clash 
since it's a template - Thread(DataIndex). Should I file a bug 
suggesting a name change? Or maybe D ought to allow both 
parameterised and normal types to have the same name - C# for 
example allows it.