使用&和Intptr的指针声明语法.两者都相同吗?

var*_*ble 7 c#

情况1:

int i;
int* pi = &i;
Run Code Online (Sandbox Code Playgroud)

案例2:

int i;
IntPtr pi = &i;
Run Code Online (Sandbox Code Playgroud)

这两种情况都一样吗?

我的目的是: -

  1. 我正在将值复制到字符串变量.
  2. 将字符串转换为字节数组
  3. 使用Marshal.Alloc(sizeofBytesArray)获取IntPtr ptrToArray
  4. marshal.copy(阵列,0,ptrToArray,sizeofBytesArray)
  5. 通过使用结构并通过SendMessage win32 api传递结构将此ptrToArray发送到vb6应用程序.

在VB6应用程序: -

  1. 我从结构中获取值,该结构为我提供了数组的地址.
  2. 使用CopyMemory将bytesarray数据复制到字符串中..

更多代码:

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);
...............
Run Code Online (Sandbox Code Playgroud)

Pra*_*hal 1

根据 msdn 页面:-

IntPtr 类型可由支持指针的语言使用,并且可以作为在支持和不支持指针的语言之间引用数据的通用方法。

IntPtr 对象也可用于保存句柄。例如,IntPtr 的实例在 System.IO.FileStream 类中广泛使用来保存文件句柄。

两种情况是否相同?

不,它们并不相同,区别在于底层实现IntPtr

外汇

  int i = 10 ; 
  int *pi = i ; 
  int c = *pi ; // would work 
Run Code Online (Sandbox Code Playgroud)

但要做同样的事情,你必须转换IntPtr为 int*

 int i =10 ; 
 IntPtr pi = &i ; 
 int *tempPtr = (int*)pi ; 
 int c = *tempPtr ; 
Run Code Online (Sandbox Code Playgroud)

的内部表示IntPtr类似于 void*,但它像整数一样公开。每当您需要存储非托管指针并且不想使用不安全代码时,都可以使用它。

它有两个限制:

  1. 它不能直接取消引用(您必须将其转换为真正的指针)。
  2. 它不知道它指向的数据的类型。(因为void*)