tags:

views:

70

answers:

3

Hi,

When I make some P/Invoke or COM InterOP, I often bump into the IntPtr. So here is a couple of questions:

  • Everyone said that IntPtr is a struct, so what's in it? I can only think of an 32bit/64bit integer which is the address it points to. Anything else?

  • Where is the IntPtr located? If it is a struct, I believe it should be in the CLR managed stack. But what if I pass an IntPtr to an unmanaged method when doing p/invoke, isn't it passed to the unmanaged stack? Will it be copied to the unmanaged stack? There're managed and unmanaged heaps in a process address space, does this seperation also exist for a process' stack?

+2  A: 
  • Yes, it's just a pointer. That's all.

  • I think you've bought into the "structs are on the stack, classes are on the heap" myth. I strongly recommend that you read Eric Lippert's blog entry on this (and another one).

Jon Skeet
Many thanks Jon. I will read those 2 blogs and come back soon.
smwikipedia
+1  A: 

Everyone said that IntPtr is a struct, so what's in it? I can only think of an 32bit/64bit integer which is the address it points to. Anything else?

Using Reflector, you can see that it contains only one instance field, of type void*

private unsafe void* m_value;

Where is the IntPtr located? If it is a struct, I believe it should be in the CLR managed stack. But what if I pass an IntPtr to an unmanaged method when doing p/invoke, isn't it passed to the unmanaged stack? Will it be copied to the unmanaged stack? There're managed and unmanaged heaps in a process address space, does this seperation also exist for a process' stack?

First, structs are not necessarily stored on the stack. This is a common misconception: they can be stored on the stack, but it doesn't mean it's always the case (see this article for details).

Also, there is no "process stack": each thread has its own stack.

I don't know all the details of how p/invoke works, but basically, yes, the IntPtr value is copied to unmanaged memory.

If you want more information about interop with unmanaged code, you might be interested in this article.

Thomas Levesque
+3  A: 

An IntPtr is simply an integer that is guaranteed to be the size of a pointer. Because of that, it is often used to contain pointers in contexts where it would be considered "unsafe" to have a pointer.

But, like a pointer, it's just a number. If it contains an address then the address could be valid or invalid in this process. It could be aligned or unaligned, it could be to a location on the current thread's stack or another thread's stack or the managed heap or some unmanaged heap. It's just a number; whether the interpretation of that number as a pointer is meaningful or safe is up to you to determine.

Eric Lippert