问题描述
- C#调用DLL结构体,第一次成功,第二次的时候就报错。尝试读取或写入受保护的内存。
-
C++代码
typedef struct tagIDCardData{
char Name[32]; //姓名char Sex[6]; //性别
char Nation[20]; //名族
char Born[18]; //出生日期
char Address[72]; //住址
char IDCardNo[38]; //身份证号
char GrantDept[32]; //发证机关
char UserLifeBegin[18]; // 有效开始日期
char UserLifeEnd[18]; // 有效截止日期
char reserved[38]; // 保留
char PhotoFileName[255];// 照片路径
}IDCardData;
int _stdcall Syn_ReadMsg( int iPort,int iIfOpen,IDCardData *pIDCardData );C#代码
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct IDCardData{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string Name; //姓名
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 6)]
public string Sex; //性别
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]
public string Nation; //名族
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 18)]
public string Born; //出生日期
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 72)]
public string Address; //住址
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 38)]
public string IDCardNo; //身份证号
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string GrantDept; //发证机关
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 18)]
public string UserLifeBegin; // 有效开始日期[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 18)]
public string UserLifeEnd; // 有效截止日期[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 38)]
public string reserved; // 保留[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 255)]
public string PhotoFileName; // 照片路径}
[DllImport("SynIDCardAPI.dll", EntryPoint = "Syn_ReadMsg", CharSet = CharSet.Ansi)]
public static extern int Syn_ReadMsg(int iPortID, int iIfOpen, ref IDCardData pIDCardData);
应用代码
public int nRet=0;pulblic int nPort=1001;private void ListenCard(){
try
{
while (!_bListenCardQuit)
{
IDCardData CardMsg = new IDCardData();
nRet = Syn_ReadMsg(nPort, 0, ref CardMsg);//读取信息
GC.Collect(2, GCCollectionMode.Optimized);Thread.Sleep(500);
}
_bQuitListenCardDone = true;
#region 异常catch (Exception eE)
{
}
#endregion
}
运行到这里( nRet = Syn_ReadMsg(nPort, 0, ref CardMsg);//读取信息),第一次成功,运行第二次的时候就报错:出现尝试读取或写入受保护的内存。这通常指示其他内存已损坏!
恳请各位大牛帮忙解决一下问题啊!
解决方案
尝试一下吧文件设置为可读写状态