c++代码
有一结构:typedef struct _SC_CONTEXT{
long hPort;
DWORD dwCardType;
BYTE params[24];
} SC_CONTEXT;
有一函数:SCREADER_API void WINAPI SCCard_InitContext(long hPort,DWORD dwCardType,SC_CONTEXT* hContext);使用了上述结构在c#中这样转:
结构:   [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        public struct SC_CONTEXT
        {
            [MarshalAs(UnmanagedType.I8)]
            public long hPort;
            [MarshalAs(UnmanagedType.U8)]
            public ulong dwCardType;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 24)]
            public byte[] Params;        }
函数:   [DllImport("screader.dll", EntryPoint = "SCCard_InitContext")]
        public static extern void SCCard_InitContext(long port, long dwCardType, ref SC_CONTEXT m_Context);调用:ReaderDLL.SCCard_InitContext(ret,ReaderDLL.RFTYPE_ISO15693, ref m_Context1);
报错信息:尝试读取或写入受保护的内存。这通常指示其他内存已损坏。谁能帮小弟分析下原因啊,万分感谢哦!

解决方案 »

  1.   

    m_Context1的声明:ReaderDLL.SC_CONTEXT m_Context1;
                     m_Context1=new ReaderDLL.SC_CONTEXT();
      

  2.   

    在c#中这样转:
    结构:  [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
            unsafe public struct SC_CONTEXT
            {
                
                public long hPort;
                
                public ulong dwCardType;
                
                fixed public byte Params[24];        }
    函数:  [DllImport("screader.dll", EntryPoint = "SCCard_InitContext")]
            unsafe public static extern void SCCard_InitContext(long port, long dwCardType,  SC_CONTEXT* m_Context); 
      

  3.   

    ReaderDLL.SC_CONTEXT* m_Context1;
    报错:Pointers and fixed size buffers may only be used in an unsafe context
      

  4.   

    long hPort; 
    DWORD dwCardType;
    这两个都是32位的C#的long是64位的。