日期:2014-05-18 浏览次数:21556 次
// 编译: csc.exe /unsafe Program.cs
using System;
using System.Runtime.InteropServices; 
class Program
{ 
  public unsafe int Test<T>(T t) where T:struct 
  { 
    // 我要计算结构的大小 
    int size = Marshal.SizeOf(typeof(T)); // <-- 可以 
    byte[] buf = new byte[size]; 
    // 我要用T的指针 
    T* p = &t;                            // <-- 错误 
    return size; 
  } 
}
------解决方案--------------------
指针必须unsafe声明
------解决方案--------------------
即使与 unsafe 关键字一起使用时,也不允许获取托管对象的地址或大小或者声明指向托管类型的指针。
------解决方案--------------------
// 编译: csc.exe /unsafe Program.cs
using System;
using System.Runtime.InteropServices; 
struct Struct001
{
  int  i;
  long j;
  char k;
}
struct Struct002
{
  int i;
  string s;  // <-- 因为 string 是托管类型,所以无法获得 Struct002 的指针
}
class Program
{ 
  public unsafe int Test<T>(T t) where T:struct 
  { 
    // 我要计算结构的大小 
    int size = Marshal.SizeOf(typeof(T)); // <-- 可以 
    byte[] buf = new byte[size]; 
    // 可以获取非托管类型或由非托管类型构成的结构的指针
    Struct001  t1;
    Struct001* p1 = &t1;                  // <-- 可以
    // 不能获取托管类型或由托管类型构成的结构的指针
    Struct002  t2;
    Struct002* p2 = &t2;                  // <-- 错误 CS0208
    
    // 因为T未知,不知其成员是否含有托管类型,所以无法获得其指针 
    T* p = &t;                            // <-- 错误 CS0208 
    return size; 
  } 
}
------解决方案--------------------
下列类型都可以是指针类型:
sbyte、byte、short、ushort、int、uint、long、ulong、char、float、double、decimal 或 bool。
任何枚举类型。
任何指针类型。
仅包含非托管类型的字段的任何用户定义的结构类型。
------解决方案--------------------
噢。
------解决方案--------------------
上边说的已经很明白了.
------解决方案--------------------
OK
------解决方案--------------------
Marshal.SizeOf(typeof(T));
这个就可以了,要想让net去接管指针,则必须先转到非托管对象上
------解决方案--------------------
学习学习...
------解决方案--------------------