Convert Pointer to string

Asked

Viewed 2,790 times

0

Hello,

I would like to know how to convert from Pointer to string, because when I try to use Pointer in a Messageboxa for example, it makes me the following error:

Imagem de erro

I’m trying to get the message out like this:

 MessageBoxA(0, Pointer ,nil,0);

3 answers

3

The Pointer and the pointer definition Delphi, some kind of dice. A pointer stores the address of a variable that is in memory, and through it you can access the value of the variable that the pointer is pointing to.

Example, accessing a string variable:

procedure TForm1.Button1Click(Sender: TObject);
var
  pExemplo: Pointer;
  vStr, r: string;
begin
  vStr := 'exemplo ponteiro';

  pExemplo := @vStr;//pExemplo recebe o endereço de vStr.

  r := string(pExemplo^);//Aqui é feita a conversão da variável para string. 

  ShowMessage(r);
end;

The variable r received the value of vStr through the pointer pExemplo.

More about pointers in Delphi here. I hope I’ve helped you.

2

After searching a little more, I discovered that I must first transform it into Integer ( Integer(Pointer) and then convert it into string ( Inttostr( Int ) )

Code would look like this: IntToStr(integer( Pointer ))

  • This expression is wrong, not to convert the Pointer, vc have to convert the Pointer type variable.

  • I just didn’t express myself right, but you’re right.

0

Let the compiler help you. Use PChar, is the safest and easiest way to do.

int WINAPI MessageBox(
  _In_opt_ HWND    hWnd,
  _In_opt_ LPCTSTR lpText,
  _In_opt_ LPCTSTR lpCaption,
  _In_     UINT    uType
);

MessageBox(0, PChar('Teste'), PChar('Titulo'), MB_OK);

However, in most cases I would use:

First of all:

uses Dialogs;
ShowMessage(const Msg: String);

Second

uses Forms;
Application.MessageBox(Text, Caption: PChar; Flags: LongInt = MB_OK);

If you ever migrate your application to Unicode, you don’t want to call the function MessageBoxA, because if your string is Unicode (probably if you declare your variable as string), your code may fail.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.