定义如下函数
extern "C" __int16 __stdcall readCard(UCHAR* a1, UCHAR* a2)
{
UCHAR buf[256];
int i;
HANDLE icdev2; //通信设备句柄
icdev2 = auto_init(0,9600);
if(srd(0,0,256,buf)==0) //读成功
{
//返回串1
a1[0]=(buf[0]>>4)+0x30;
a1[1]=(buf[0]&0x0f)+0x30;
a1[2]=(buf[1]>>4)+0x30;
a1[3]=(buf[1]&0x0f)+0x30;
a1[4]=(buf[2]>>4)+0x30;
a1[5]=(buf[2]&0x0f)+0x30;
a1[6]=(buf[3]>>4)+0x30;
a1[7]=(buf[3]&0x0f)+0x30;
a1[8]=0;
//串二
i=buf[21]*256+buf[22];
a2[0]=((i/1000)%10)+0x30;
a2[1]=((i/100)%10)+0x30;
a2[2]=((i/10)%10)+0x30;
a2[3]=(i%10)+0x30;
a2[4]=0;
}
return 0;}
输出dll在调试时添加一个对话框工程
按纽事件如下:
UCHAR cardSN,price1;
int ret=readCard(&cardSN,&price1); if(ret!=0)
{
AfxMessageBox("读卡失败") ;
}
请问为什么会报错,跟踪函数工程,发现,ret返回0,但a1不是自己需要的值,且最后报错:
unhandle exception in **.exe 0xC00000005:access violation
extern "C" __int16 __stdcall readCard(UCHAR* a1, UCHAR* a2)
{
UCHAR buf[256];
int i;
HANDLE icdev2; //通信设备句柄
icdev2 = auto_init(0,9600);
if(srd(0,0,256,buf)==0) //读成功
{
//返回串1
a1[0]=(buf[0]>>4)+0x30;
a1[1]=(buf[0]&0x0f)+0x30;
a1[2]=(buf[1]>>4)+0x30;
a1[3]=(buf[1]&0x0f)+0x30;
a1[4]=(buf[2]>>4)+0x30;
a1[5]=(buf[2]&0x0f)+0x30;
a1[6]=(buf[3]>>4)+0x30;
a1[7]=(buf[3]&0x0f)+0x30;
a1[8]=0;
//串二
i=buf[21]*256+buf[22];
a2[0]=((i/1000)%10)+0x30;
a2[1]=((i/100)%10)+0x30;
a2[2]=((i/10)%10)+0x30;
a2[3]=(i%10)+0x30;
a2[4]=0;
}
return 0;}
输出dll在调试时添加一个对话框工程
按纽事件如下:
UCHAR cardSN,price1;
int ret=readCard(&cardSN,&price1); if(ret!=0)
{
AfxMessageBox("读卡失败") ;
}
请问为什么会报错,跟踪函数工程,发现,ret返回0,但a1不是自己需要的值,且最后报错:
unhandle exception in **.exe 0xC00000005:access violation
UCHAR *cardSN,*price1;
int ret=readCard(cardSN,price1);编辑通过,但结果又报同样的错
我是VC新手,一定要支持
函数里面直接对传入的指针进行赋值操作了,因此你必须保证传入的指针指向的内存空间是有效的。
UCHAR *cardSN,*price1; 只是声明指针是不够的,因为没有指向有效的空间。
这里你可以用两个缓冲区数组来保存。
UCHAR cardSN[256],price1[256]
或者动态申请内存UCHAR *cardSN = new UCHAR[256],*price1 = new UCHAR[256],
动态申请的数组空间,再不需要时需要用delete[]进行释放。
readCard(cardSN,price1);
这两个参数都是指针变量而已,指向的地方是未定义的
price1作为a2传进去可以获得正确值吗?
应该也是错误的才对,或者即使你现在调试是正确的,也
不可以这么用,可能指针刚好指向了那个位置……
a1,a2 指向的空间至少有10个字节,因此不能使用
UCHAR cardSN,price1;
int ret=readCard(&cardSN,&price1); 只有一个字节的空间UCHAR *cardSN,*price1;
int ret=readCard(cardSN,price1); 指针未分配空间应该 uchar cardsn[16],price1[16];
这样就没有问题了
readCard(cardSN,price1);
保证传入的指针指向的内存空间是有效的。
UCHAR *cardSN,*price1;
要指向有效的空间。
这里你可以用两个缓冲区数组来保存。