gpt4 book ai didi

c# - 使用 & 和 Intptr 的指针声明语法。两者相同吗?

转载 作者:太空狗 更新时间:2023-10-29 20:39:26 30 4
gpt4 key购买 nike

案例一:

int i;
int* pi = &i;

案例二:

int i;
IntPtr pi = &i;

两种情况是否相同?

我的目的是:-

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

在 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);
...............

最佳答案

根据msdn页面:-

The IntPtr type can be used by languages that support pointers, and as a common means of referring to data between languages that do and do not support pointers.

IntPtr objects can also be used to hold handles. For example, instances of IntPtr are used extensively in the System.IO.FileStream class to hold file handles.

两种情况是否相同?

不,它们不相同,区别在于 IntPtr

的底层实现

外汇

  int i = 10 ; 
int *pi = i ;
int c = *pi ; // would work

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

 int i =10 ; 
IntPtr pi = &i ;
int *tempPtr = (int*)pi ;
int c = *tempPtr ;

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

它有两个限制:

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

关于c# - 使用 & 和 Intptr 的指针声明语法。两者相同吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21280765/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com