日期:2014-05-18  浏览次数:20951 次

Intptr是Struct数组的起始地址,如何获取数组中其他Struct值
调用C++方法返回数组首地址
C# code
IntPtr returnIntPtr = PictureMatching.GetMatchingResult(ref result_size,sbSimpleFilePath.ToString(),sbSelectedPictruePath.ToString(), intMatchingType, rect);



这样写可以获得数组中第一个Struct值
C# code
PicMatchingResult testPicMatchingResult = (PicMatchingResult)Marshal.PtrToStructure(returnIntPtr, typeof(PicMatchingResult));


returnIntPtr是数组起始地址,result_size是数组长度,从起始地址我可以获得该Struct正确的值,但是如何得到数组其他元素?

望指教!

------解决方案--------------------
C# code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace WindowsFormsApplication14
{
    struct S
    {
        public int a;
        public int b;
    }

    public partial class Form1 : Form
    {

        public Form1()
        {

            InitializeComponent();

            S[] s = new S[2]
            {
               new S()
               {
                   a=1,
                   b=11
               },
               new S()
               {
                   a=2,
                   b=22
               }
            };

            //for (int i = 0; i < 2; i++)
            //{
            //    IntPtr P = Marshal.UnsafeAddrOfPinnedArrayElement(s, i);
            //    S A = (S)Marshal.PtrToStructure(P, typeof(S));
            //    MessageBox.Show("a=" + A.a + "  b=" + A.b);
            //}

            IntPtr P = Marshal.UnsafeAddrOfPinnedArrayElement(s, 0);
            S A = (S)Marshal.PtrToStructure(P, typeof(S));
            MessageBox.Show("a=" + A.a + "  b=" + A.b);
            P = new IntPtr(P.ToInt32() + Marshal.SizeOf(A));
            A = (S)Marshal.PtrToStructure(P, typeof(S));
            MessageBox.Show("a=" + A.a + "  b=" + A.b);
        }
    }
}