哦,C#到底有没有指针的概念啊?我看到网上有很多种说辞,有的说有,要用unsafe,有的说没有。
我也试过用unsafe,如下:
public unsafe struct SISO180006CCUSTOMCMDRESULT 
{
   ...
};
private void btn1_Click(object sender, EventArgs e)
{
  unsafe
  {
    SISO180006CCUSTOMCMDRESULT *pCustomCmdResult;
  }
}
但编译老是出现这个错误:error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type 
我已经加了unsafe修饰结构体了,不是就把该结构体定义为managed type了吗?

解决方案 »

  1.   

    不需要使用指针。在C#中定义好兼容的结构体,用Marshal分配空间,再传递给dll。
      

  2.   

    C#的指针自己去MSDN找指针的说明。
      

  3.   

    别指望在C#里使用指针了,哪怕是所谓的unsafe状态下指针也是限制极多。
      

  4.   

    在C#里不叫指针,而叫引用
    用unsafe是可以显示调用指针的,但不建议这么做
      

  5.   

    可以写一个简单的例子如何在C#中调用C++的二级指针吗?
    比如,下面的C++代码,在C#中要怎么写 :
    void fun1(TStudent **pp)
    {
      (*p) = malloc(sizeof(TStudent));
      ...
    }
    void main()
    {
      TStudent  *p = NULL;
      fun1(&p);
      free(*p);
      *p = NULL;
    }
    那在C#要写如何写main()函数来调用fun1()啊?
      

  6.   

    既然熟悉C++,先了解一下PInvoke的基本知识,再用C#写PInvoke调用
    TStudent p = null;
    fun1(out p);
    关键字对应
    in ==> ref
    out ==> out个人建议是加一层C++/CLI的封装,方便快捷.
      

  7.   

    学习难度C++/CLI>C++>C#,最重要的是,C++/CLI编程没有智能语法提示,编译器(最新的11除外)不支持C++/CLI的语法检测。因此用C++/CLI封装还不如用C#直接调用,封装难度比直接调用更大。
      

  8.   


    难与不难,看个人,智能提示只是辅助,你可以说的更委婉些.个人觉得,学习难度C++/CLI>C++>C#....
      

  9.   


    void fun1(TStudent **pp)
    {
      (*p) = malloc(sizeof(TStudent));
      ...
    }[StructLayout(LayoutKind.Sequential)]
    public struct TStudent {
        public int age;
    }[DllImport(DllName, CharSet = CharSet.Auto, EntryPoint = "fun1")]
    static extern void fun(ref Intptr student);//
    //使用的时候
    //
    public TStudent Get(){
       int size = Marshal.SizeOf(typeof (TStudent));
       IntPtr ptr = Marshal.AllocHGlobal(size);
    try
       fun(ref Intptr ptr);
    }finally {
      Marshal.FreeHGlobal(ptr);
    }
    }
    //
    //排版不好,会有一些错误,大致思路是这样的^_^
    //
      

  10.   

    哦,非常感谢大家的解答!我运行了楼上兄弟wodegege10的代码,perfect!
    可以再请教一个问题吗?我想用到C的共用体union,因此,我改成了这样,但是为什么一运行就会出错呢?
    [StructLayout(LayoutKind.Explicit)]
    public struct TStudent {
        [FieldOffset(0)]
        public int age;
        
        [FieldOffset(0)]
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)]
        public byte[] b1;
    }[DllImport(DllName, CharSet = CharSet.Auto, EntryPoint = "fun1")]
    static extern void fun(ref Intptr student);//
    //使用的时候
    //
    public TStudent Get(){
       int size = Marshal.SizeOf(typeof (TStudent));
       IntPtr ptr = Marshal.AllocHGlobal(size);
    try
       fun(ref Intptr ptr);
    }finally {
      Marshal.FreeHGlobal(ptr);
    }
    }
      

  11.   

    为什么像下面这样用不行呢?IntPtr ptr;
    fun(ref IntPtr ptr);