调用外部DLL,函数声明问题
函数原型:
BYTE Read_Guest_Card( BYTE AReaderType, BYTE ACardType, BYTE APort,
BYTE ASector, BYTE ABlock,
BYTE * AHotelPwd,
int ALockNo, BYTE AStartSuite, BYTE AEndSuite,
int ACardID, int ASubCardID,
char * ATime )
函数声明:
[DllImport("btLock56.dll", EntryPoint = "Read_Guest_Card")]
private static extern byte ReadGuestCard(byte AReaderType, byte ACardType, byte APort, byte ASector, byte ABlock,
byte[] AHotemPwd, int ALockNo, byte AStartSuite, byte AEndSuite, int ACardID, int ASubCardID,
char[] ATime);
调用:
byte[] dHotelPWD = new byte[8];
char[] dYltime = new char[10];
int i=ReadGuestCard(dkqType, kType, portSN, aSector, 0,
dHotelPWD, lockNum, 0, 0, 1, 0,
dYltime);
这段代码,在调用的时候会报这个错误:
尝试读取或写入受保护的内存。这通常指示其他内存已损坏。
应该就是这个数据类型转换的问题,我试过好几种了,都是同样的错误
原型里的两个指针都是返回类型
C#里我要用什么类型?
------解决方案--------------------如果是要返回型的char* 就用 StringBuilder
------解决方案--------------------实在不行你启用不安全模式 unsafe,然后这样声明DLL
DllImport("btLock56.dll", EntryPoint = "Read_Guest_Card")]
private unsafe static extern byte ReadGuestCard(byte AReaderType, byte ACardType, byte APort, byte ASector, byte ABlock, byte* AHotemPwd, int ALockNo, byte AStartSuite, byte AEndSuite, int ACardID, int ASubCardID, byte* ATime);
调用:
unsafe
{
byte[] dHotelPWD = new byte[8];
byte[] dYltime = new byte[10];
fixed(byte* pHotelPWD = dHotelPWD, pYltime=dYltime)
int i=ReadGuestCard(dkqType, kType, portSN, aSector, 0,pHotelPWD , lockNum, 0, 0, 1, 0, pYltime);
}
这里为什么不用char* 是因为C#的char类型是两个字节,而C++是一个字节