【问题标题】:Differences of pointers between unmanaged C++ and managed C++非托管 C++ 和托管 C++ 指针的区别
【发布时间】:2016-04-13 08:19:04
【问题描述】:

由于非托管 C++ 可以随意定位到不同的对象。 比如指向数组的指针

int pt[50];
int* pointer = pt;

我们可以直接使用 *pointer 来获取数组中元素的第一个值。 因此,我们也可以使用 *(pointer++) 来指向第二个元素。

但是,如果可以直接使用^(pointer+5) 来获取数组的第六个元素呢? 示例如下。

array<int>^ pt = gcnew array<int>(50);
int^ pointer = pt;

如何使用指针作为媒介来访问数组中的不同元素?

【问题讨论】:

    标签: windows pointers c++-cli managed-c++


    【解决方案1】:

    这里有一个稍微不同的方法,可能有用......

    它使用内部指针算法(遍历数组)。

    希望这会有所帮助。

    using namespace System;
    
    ref class Buf
    {
        // ...
    };
    
    int main()
    {
       array<Buf^>^ array_of_buf = gcnew array<Buf^>(10);
    
       // Create a Buf object for each array position
       for each (Buf^ bref in array_of_buf)
       {
          bref = gcnew Buf();
       }
    
       // create an interior pointer to elements of the array
       interior_ptr<Buf^> ptr_buf;
    
       // loop over the array with the interior pointer
       // using pointer arithmetic on the interior pointer
       for (ptr_buf = &array_of_buf[0]; ptr_buf <= &array_of_buf[9]; ptr_buf++)
       {
          // dereference the interior pointer with *
          Buf^ buf = *ptr_buf;
          // use the Buf class
       }
    }
    

    参考:C++/CLi .net 的可视化 c++ 语言(第 99 页)

    这里是另一个例子:https://msdn.microsoft.com/en-us/library/y0fh545k.aspx

    // interior_ptr.cpp
    // compile with: /clr
    using namespace System;
    
    ref class MyClass {
    public:
       int data;
    };
    
    int main() {
       MyClass ^ h_MyClass = gcnew MyClass;
       h_MyClass->data = 1;
       Console::WriteLine(h_MyClass->data);
    
       interior_ptr<int> p = &(h_MyClass->data);
       *p = 2;
       Console::WriteLine(h_MyClass->data);
    
       // alternatively
       interior_ptr<MyClass ^> p2 = &h_MyClass;
       (*p2)->data = 3;
       Console::WriteLine((*p2)->data);
    }
    

    【讨论】:

      猜你喜欢
      • 2011-07-03
      • 2011-11-11
      • 1970-01-01
      • 1970-01-01
      • 2011-04-03
      • 2011-07-12
      • 2017-08-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多