What is the differences between int* and IntPtr ?

Arsium ***** 331 Reputation points
2021-01-12T11:56:42.717+00:00

Just curious about the difference of those things in C# : int* and IntPtr ?

And also :

int varTest = 123;

IntPtr PT = (IntPtr)(&varTest);

int* PointerTo = &varTest;

long LongAdd = (long)PointerTo;

int IntAdd = (int)PointerTo;

MessageBox.Show(LongAdd.ToString());  //Same
MessageBox.Show(IntAdd.ToString());  //Same
MessageBox.Show(PT.ToString());  //Same
Developer technologies | C#
0 comments No comments
{count} vote

Accepted answer
  1. Daniel Zhang-MSFT 9,656 Reputation points
    2021-01-13T06:00:37.303+00:00

    Hi Arsium-4135,
    int* i means that the type of i is "pointer to int" and you read it as i is a pointer to an integer.
    That is to say , the first part represents the variable type (pointer to int), and the second part represents the name (i).
    The IntPtr type is designed to be an integer whose size is platform-specific. That is, an instance of this type is expected to be 32-bits on 32-bit hardware and operating systems, and 64-bits on 64-bit hardware and operating systems.
    It is called IntPtr because to use it from unmanaged native code C/C++, you will have to use the analog type: intptr_t. C#'s IntPtr is fully mapped to C/C++'s intptr_t. It may be implemented as intptr_t. In C/C++, ensure that the size of intptr_t type is the same as the size of void* type.
    And you need to put your code into unsafe{...}.
    More details you can refer to the following links.
    Just what is an IntPtr exactly?
    IntPtr Struct
    Best Regards,
    Daniel Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.