调用DLLImport方法时出现AccessViolationException

时间:2018-09-24 14:41:58

标签: c# arrays dllimport access-violation

对于Mifare Reader,我收到了带有dll的示例代码。在DemoApp上,一切正常(WinForms)正常运行,但是当我尝试在.NET API应用中执行此代码时,会出现AccessViolationException。

public string readBlock(String Block)
        {

            byte mode1 = (byte)0x00;
            byte mode2 = (byte)0x00;
            byte mode = (byte)((mode1 << 1) | mode2);
            byte blk_add = Convert.ToByte(Block, 16);
            byte num_blk = Convert.ToByte("01", 16);
            byte[] snr = new byte[6];
            snr = convertSNR("FF FF FF FF FF FF", 6);

            byte[] buffer = new byte[16 * num_blk];

            int nRet = MF_Read(mode, blk_add, num_blk, snr, buffer); 
}

[DllImport("function.dll", CallingConvention = CallingConvention.StdCall)]
        public static extern int MF_Read(byte mode, byte blk_add, byte num_blk, [In]byte[] snr, [In]byte[] buffer);

我尝试使用GCHandle和Marshal将byte []转换为IntPtr,但仍然无法正常工作。

            byte[] buffer = new byte[16 * num_blk];
            GCHandle pinned = GCHandle.Alloc(buffer, GCHandleType.Pinned);
            IntPtr buff = pinned.AddrOfPinnedObject();
            GCHandle pinned2 = GCHandle.Alloc(snr, GCHandleType.Pinned);
            IntPtr snr1 = pinned2.AddrOfPinnedObject();
            int nRet = CardGate.MF_Read(mode, blk_add, num_blk, snr1, buff);
            pinned.Free();

0 个答案:

没有答案