下面的代码运行正常,可以正常获取到值
        [DllImport(@"D:\Visual Studio 2005\teste\release\teste.dll")]
        private static extern IntPtr Test(int[] m);
        public int[] myTest(int[] m)
        {
            IntPtr ptr = Test(m);
            int[] result = new int[m.Length];
            Marshal.Copy(ptr,result,0,m.Length);
            return result;
        }下面的代码在上面的基础上将int[] result 改为了 MacInfoSt[] result ,(MacInfoSt为自定义结构体),
会提示 “Marshal.Copy 最匹配的重载方法具有一些无效参数”的错误??请大家指教!        [DllImport(@"D:\Visual Studio 2005\teste\release\teste.dll")]
        private static extern IntPtr Querys(uint[] loginid);
        public MacInfo[] myQuerys(uint[] loginid)
        {
            IntPtr ptr = Querys(loginid);
            MacInfoSt[] result = new MacInfoSt[loginid.Length];
            Marshal.Copy(ptr, result, 0, loginid.Length);
            return result;
        }

解决方案 »

  1.   

    l楼主, Marshal.Copy16个重载函数,没有一个是结构体的,编译器当然会报这个错误
      

  2.   

    [DllImport(@"D:\Visual Studio 2005\teste\release\teste.dll")]
            private static extern IntPtr Querys(uint[] loginid);
            public MacInfo[] myQuerys(uint[] loginid)
            {
                IntPtr ptr = Querys(loginid);
                MacInfoSt[] result = new MacInfoSt[loginid.Length];
                for(int i = 0;i<loginid.Length;i++)
                    result[i] = (MacInfoSt)Marshal.PtrToStructure(ptr + i * sizeof(MacInfoSt),typeof(MacInfoSt));
                return result;
            }
    这个返回的ptr是由调用方来释放的?那不用copy,直接转为MacInfoSt指针使用完再释放就行了啊。
      

  3.   


    调试时出现如下错误:错误 1 “MacInfoSt”没有预定义的大小,因此 sizeof 只能在不安全的上下文中使用(请考虑使用 System.Runtime.InteropServices.Marshal.SizeOf) D:\visual studio 2010\Projects\WcfService4\Service1.svc.cs 271 77 WcfService4该怎么解决??
      

  4.   

    这样就可以了:(MacInfoSt)Marshal.PtrToStructure(ptr + i * Marshal.SizeOf(typeof(MacInfoSt)), typeof(MacInfoSt));
      

  5.   


    这样做时发现一个奇怪的问题,当i>=4时,取到的值就乱掉了???怎么会这样??有人知道吗????
      

  6.   

    问题应该处在这里:IntPtr ptr = Querys(loginid);你的Querys代码怎么写的
      

  7.   


    C++自定义结构体中的 char* name,在C#对应的自定义结构体中写成IntPtr name;会有问题么?????
      

  8.   

    char* name 对应string name