Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer declaration syntax using & and Intptr. Are both identical?

Tags:

c#

Case 1:

int i;
int* pi = &i;

Case 2:

int i;
IntPtr pi = &i;

Are both cases identical?

My purpose is that:-

  1. I am copying a value to string variable.
  2. Converting string to bytes array
  3. using Marshal.Alloc(sizeofBytesArray) to get IntPtr ptrToArray
  4. marshal.copy(array,0,ptrToArray,sizeofBytesArray)
  5. Sending this ptrToArray to a vb6 application by using a structure and passing structure via SendMessage win32 api.

On VB6 app:-

  1. I am picking up the value from the structure that gives me the address of the array.
  2. using CopyMemory to copy the bytesarray data into a string..

More Code:

string aString = text;
            byte[] theBytes = System.Text.Encoding.Default.GetBytes(aString);

            // Marshal the managed struct to a native block of memory.
            int myStructSize = theBytes.Length;
            IntPtr pMyStruct = Marshal.AllocHGlobal(myStructSize); //int* or IntPtr is good?
            try
            {
                Marshal.Copy(theBytes, 0, pMyStruct, myStructSize);
...............
like image 317
variable Avatar asked Jan 22 '14 10:01

variable


1 Answers

According to the msdn page:-

The IntPtr type can be used by languages that support pointers, and as a common means of referring to data between languages that do and do not support pointers.

IntPtr objects can also be used to hold handles. For example, instances of IntPtr are used extensively in the System.IO.FileStream class to hold file handles.

Are both cases indentical?

No, they are not identical, The difference is in the underlying implementation of IntPtr

forex

  int i = 10 ; 
  int *pi = i ; 
  int c = *pi ; // would work 

but to do the same thing , you have to cast IntPtr to int*

 int i =10 ; 
 IntPtr pi = &i ; 
 int *tempPtr = (int*)pi ; 
 int c = *tempPtr ; 

The internal representation of IntPtr is like void* but it is exposed like an integer. You can use it whenever you need to store an unmanaged pointer and don't want to use unsafe code.

It has two limitations:

  1. It cannot be dereferenced directly (you have to cast it as a true pointer).
  2. It doesn't know the type of the data that it points to. (because of void*)
like image 183
Pratik Singhal Avatar answered Oct 03 '22 13:10

Pratik Singhal