Sandeep
Sandeep

Reputation: 420

How to Convert IntPtr to native c++ object

I have COM dll that I am using in C++/Cli, one of the method in this COM dll returns IntPtr I want to convert that back to the native object pointer. How I can do that ? please in put

Upvotes: 8

Views: 16055

Answers (3)

Hans Passant
Hans Passant

Reputation: 942438

IntPtr is an integral type, you need to first convert it to a pointer type:

  IntPtr somePtr;
  ...
  Mumble* fooPtr = (Mumble*)(void*)somePtr;

Or the more readable version:

  Mumble* fooPtr = (Mumble*)somePtr.ToPointer();

The method call will be optimized away at runtime.

Upvotes: 14

Asad Mehmood
Asad Mehmood

Reputation: 514

I would like to modify Hans Passant's answer,
IntPtr directly returns void pointer .. which you can cast easily in any type of native C++ Pointer.

IntPtr somePtr;
Mumble* fooPtr = (Mumble*)somePtr.ToPointer();

here .ToPointer() will return void pointer, now you can cast to your custom pointer type.

Upvotes: 3

Tim Robinson
Tim Robinson

Reputation: 54764

IntPtr has a ToPointer method that returns a void*. Call this method, then use reintepret_cast to cast this pointer to the right native type.

Upvotes: 8

Related Questions