WindowsAPI - Problem with DECLARE_HANDLE definition

Simen Kjaeraas simen.kjaras at gmail.com
Fri Sep 20 08:59:09 PDT 2013


On 2013-09-19, 10:06, Kagamin wrote:

> On Wednesday, 11 September 2013 at 20:20:13 UTC, Simen Kjaeraas wrote:
>> On 2013-09-11, 20:29, Andrej Mitrovic wrote:
>>
>>> On 9/11/13, Kagamin <spam at here.lot> wrote:
>>>> I'd say, strong handles shouldn't act as pointers (and shouldn't
>>>> contain pointers), so null shouldn't work.
>>>
>>> "NULL" is already used in a ton of WinAPI C/C++ code and MSDN
>>> documentation, it would be a major pain in the ass to have to use e.g.
>>> HWND(0) instead.
>>
>> How's about
>>
>>   enum NULL = HANDLE(0);
>>
>> Honestly I hate that, and am convinced the correct way to fix this is
>> for D to add opImplicitCastFrom.
>
> Or multiple alias this:
>
> struct _NULL
> {
> 	HANDLE zero;
> 	void* ptr;
> 	alias zero this;
> 	alias ptr this;
> }

If you want opaque handles, that does not solve the problem. What would
solve the problem is something like this:

struct DECLARE_HANDLE(int line = __LINE__, string file = __FILE__T) {
     private void* payload;

     private this(void* value) {
         payload = value;
     }

     ref DECLARE_HANDLE opAssign(typeof(null) value) {
         payload = null;
         return this;
     }

     DECLARE_HANDLE opImplicitCastFrom(typeof(null) value) {
         return DECLARE_HANDLE(null);
     }
}

alias DECLARE_HANDLE!(__LINE__, __FILE__) HANDLE; // BUG11074
alias DECLARE_HANDLE!(__LINE__, __FILE__) HWND;   // BUG11074

void test() {
   void* voidPointer;
   HANDLE handle;
   HWND window;

   SomeWindowsFunctionTakingAHandle(null); // No problem!
   SomeWindowsFunctionTakingAHandle(handle); // No problem!

   SomeWindowsFunctionTakingAHandle(voidPointer); //  Does not compile.
   SomeWindowsFunctionTakingAHandle(window); // Does not compile.
}
-- 
   Simen


More information about the Digitalmars-d mailing list