情况1:
int i;
int* pi = &i;
Run Code Online (Sandbox Code Playgroud)
案例2:
int i;
IntPtr pi = &i;
Run Code Online (Sandbox Code Playgroud)
这两种情况都一样吗?
我的目的是: -
在VB6应用程序: -
更多代码:
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)
根据 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*,但它像整数一样公开。每当您需要存储非托管指针并且不想使用不安全代码时,都可以使用它。
它有两个限制:
void*)| 归档时间: |
|
| 查看次数: |
822 次 |
| 最近记录: |