Convert const(GUID)* to GUID*

Jonathan M Davis jmdavisProg at gmx.com
Sat Jun 25 13:16:01 PDT 2011


On 2011-06-25 13:05, Jimmy Cao wrote:
> On Sat, Jun 25, 2011 at 2:48 PM, Loopback <elliott.darfink at gmail.com> wrote:
> > Hello!
> > 
> > I've recently been working with DirectInput using the win32 API Binding
> > at dsource.org. This wrapper has been working perfectly fine until I
> > started using GUID constants defined in win32.directx.dinput8.
> > 
> > The directx function DirectInput8Create takes these parameters:
> > HRESULT DirectInput8Create(HINSTANCE, DWORD, GUID*, void**, IUnknown);
> > 
> > For the GUID* (3rd) parameter, I specify the IID_IDirectInput8 constant.
> > This is defined in the dinput8 file as follows:
> > const GUID IID_IDirectInput8A = {...};
> > 
> > If I supply this constant to the DirectInput8Create function the
> > compiler complains saying that it cannot convert const(GUID) to GUID*.
> > If I instead use &IID_IDirectInput8 (as a reference) I get the
> > "Cannot convert const(GUID)* to GUID*" instead. So my question is; how
> > do I solve this?
> 
> I think you can cast the const away.
> cast(GUID*)&IID_IDirectInput8

Well, you _can_, but casting away const is not technically defined in D. It 
should work at this point, but it's quite legal for a D compiler to _not_ work 
with casting away const. You're really not supposed to be casting away const.

The best way to handle this is to have a GUID* which isn't const in the first 
place. Barring that, if the function that you're trying to pass it to is a C 
function, and you _know_ that that function isn't going to alter it, then you 
could always use a declaration for that function which makes the parameter 
const. If it's a D function and you know that it won't alter the variable, 
then it would probably be better to write a version of it which takes a const. 
Now, if you can't do either of those for some reason, and you _know_ that the 
function isn't going to alter the variable, then you can currently cast away 
const, and odds are that that will always work with any D compiler, but 
there's no guarantee that it will, because casting away const is undefined. 
Now, if the function actually _does_ alter the variable, then you need to get 
a mutable variable to pass to it. You'd just be asking for trouble to give a 
const variable to a function which will alter that variable, no matter how you 
manage to get the function take take it.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list