C#调用 C++ 结构体数组

C++ 结构体定义和赋值

typedef struct {
	char barcode[13];
	int num;
}Goods;
extern "C" __declspec(dllexport) bool getGoods(Goods* pGoods)
{
	for (int i = 0; i<2; i++)
	{
		sprintf(pGoods[i].barcode, "123456%d", i);
		pGoods[i].num = rand() % 10 + 1;
	}
	return true;
}

C# 结构体和取值

class Program
    {
        static void Main(string[] args)
        {
            int length = 2;
            int size = Marshal.SizeOf(typeof(Goods)) * length;
            byte[] bytes = new byte[size];
            IntPtr pBuff = Marshal.AllocHGlobal(size);
            Goods[] pClass = new Goods[length];
            getGoods(pBuff);
            //detectGoods(pBuff);
            for (int i = 0; i < length; i++)
            {
                IntPtr pPonitor = new IntPtr(pBuff.ToInt64() + Marshal.SizeOf(typeof(Goods)) * i);
                pClass[i] = (Goods)Marshal.PtrToStructure(pPonitor, typeof(Goods));

                Console.WriteLine("barcode:{0}; num:{1}", pClass[i].barcode, pClass[i].num);  
            }
            Marshal.FreeHGlobal(pBuff);
        }
        [DllImport("shelves_detect.dll", EntryPoint = "getGoods", CallingConvention = CallingConvention.StdCall)]
        public static extern bool getGoods(IntPtr p);
    }
    [StructLayout(LayoutKind.Sequential)]   
    public struct Goods
    {
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 13)]  
        public string barcode;
        public int num;
    }


你可能感兴趣的:(C++)