如何将IntPtr转换为本机c ++对象

San*_*ep 6 .net c# interop c++-cli

我有COM dll,我在C++/Cli中使用,这个COM dll中的一个方法返回IntPtr我想将其转换回本机对象指针.我怎么能这样做?请放入

Han*_*ant 12

IntPtr是一个整数类型,您需要先将其转换为指针类型:

  IntPtr somePtr;
  ...
  Mumble* fooPtr = (Mumble*)(void*)somePtr;
Run Code Online (Sandbox Code Playgroud)

或者更易阅读的版本:

  Mumble* fooPtr = (Mumble*)somePtr.ToPointer();
Run Code Online (Sandbox Code Playgroud)

方法调用将在运行时进行优化.


Tim*_*son 8

IntPtr有一个ToPointer返回a 的方法void*.调用此方法,然后使用reintepret_cast将此指针强制转换为正确的本机类型.