Victor
Victor

Reputation: 14612

What is actually an INT_PTR and how can I convert data to INT_PTR?

I am trying to use the TBBUTTON structure that Windows API provides for creating toolbar buttons. Of course I tried adding some text to those buttons, so I set the iString member of TBBUTTON structure, which is of type INT_PTR:

typedef struct {
  int       iBitmap;
  int       idCommand;
  BYTE      fsState;
  BYTE      fsStyle;
#ifdef _WIN64
  BYTE      bReserved[6];
#else 
#if defined(_WIN32)
  BYTE      bReserved[2];
#endif 
#endif 
  DWORD_PTR dwData;
  INT_PTR   iString;
} TBBUTTON, *PTBBUTTON, *LPTBBUTTON;

There is an example on MSDN which initializes that structure like this:

TBBUTTON tbButton = { MAKELONG(STD_FILENEW,  ImageListID), IDM_NEW,  TBSTATE_ENABLED, buttonStyles, {0}, 0, (INT_PTR)L"New" };

Notice the (INT_PTR)L"File" conversion there. When I do the exact same thing, I get some strange strings displayed:

I read the documentation about INT_PTR on MSDN, but I still don't understand it, because somehow, it works for them but not for me...

So how to convert that Unicode string to INT_PTR?

Upvotes: 3

Views: 6920

Answers (2)

Dai
Dai

Reputation: 155418

This is documented on MSDN under MFC. The Toolbar class is technically not part of the Windows API (Win32), but actually MFC. https://msdn.microsoft.com/en-us/library/bdabdzxd.aspx

It says:

iString

Zero-based index of the string to use as the button's label, -1 if there is no string for this button. The image and/or string whose index you provide must have previously been added to the toolbar control's list using AddBitmap, AddString, and/or AddStrings.

So casting a string isn't going to work (and in C++ always prefer C++-style casting operators over C-style casts).

AddString itself expects a Resource ID rather than a string literal. Use AddStrings to use in-memory strings.

So your code should look like this (pseudocodeish):

LPCTSTR buttonTexts = L"Button1\0Button2\0"; // single buffer containing multiple null-terminated strings, and must end with two \0 (note the last null is implicit).

CToolbarCtrl* toolbar = ...
int addStringResult = toolbar->AddStrings( buttonTexts );
if( addStringResult == -1 ) die();

TBBUTTON buttons[] = {
    { /* ... */ iString: 0 },
    { /* ... */ iString: 1 }
};
BOOL addButtonResult = toolbar->AddButtons( 2, &buttons );
if( !addButtonResult ) die();

Upvotes: 3

Ulrich Eckhardt
Ulrich Eckhardt

Reputation: 17424

INT_PTR is a type that is an integer but which has the guarantee that it has the size of a pointer. Using reinterpret_cast, you can convert between a pointer type and INT_PTR.

Now, concerning you question about a Unicode string, I don't know, because I don't know what representation of that string you have. You'll have to provide more info for that.

Upvotes: 1

Related Questions