我这样写的.
VC DLL部分
size_t *Ep2ReadLen;
extern "C" int _stdcall TestDLL(size_t* iPort2ReadLen)
{
Ep2ReadLen = iPort2ReadLen;
*Ep2ReadLen = 5; //这里
if (Ep2ReadLen)
{
free(Ep2ReadLen);
//Ep2ReadLen=NULL;
}return 0;
}VB部分
Declare Function TestDLL Lib "XXX.dll" (ByRef iPort2ReadLen As Integer) As Integer
Dim iPort2ReadLen As Integer
rt = TestDLL(iPort2ReadLen)编译通过,运行VB程序,调用,能正确返回5。但是在关闭VB程序时,报错。
但在上面的 *Ep2ReadLen = 5; 注释掉后,就不报错了。说明是这行导致的。
我曾考虑是不是VC指针没有释放,所以加上 free(Ep2ReadLen);
但结果仍然一样。
请教各位,错在哪里?
VC DLL部分
size_t *Ep2ReadLen;
extern "C" int _stdcall TestDLL(size_t* iPort2ReadLen)
{
Ep2ReadLen = iPort2ReadLen;
*Ep2ReadLen = 5; //这里
if (Ep2ReadLen)
{
free(Ep2ReadLen);
//Ep2ReadLen=NULL;
}return 0;
}VB部分
Declare Function TestDLL Lib "XXX.dll" (ByRef iPort2ReadLen As Integer) As Integer
Dim iPort2ReadLen As Integer
rt = TestDLL(iPort2ReadLen)编译通过,运行VB程序,调用,能正确返回5。但是在关闭VB程序时,报错。
但在上面的 *Ep2ReadLen = 5; 注释掉后,就不报错了。说明是这行导致的。
我曾考虑是不是VC指针没有释放,所以加上 free(Ep2ReadLen);
但结果仍然一样。
请教各位,错在哪里?
{
free(Ep2ReadLen); //空间被释放了,后续访问会导致异常
//Ep2ReadLen=NULL;
}VB部分
Declare Function TestDLL Lib "XXX.dll" (ByRef iPort2ReadLen As Integer) As Integer
Dim iPort2ReadLen As Integer//应该是指针的吧,vb我不懂
rt = TestDLL(iPort2ReadLen)
free(Ep2ReadLen);的添加不是我的本意,最先是没有加这行的,但最终关闭VB程序报错后,我增加了这行,结果相同。
我原以为是没有释放指针,导致的报错,但现在看好像又不是 :(VB好像没有指针?
好,我去掉这句。但去掉之后,最后关闭VB程序还是如此,我怀疑VB先把自己的iPort2ReadLen 释放掉了,才释放DLL,导致出错,判断是否正确?
我又试了一下测试一:Dim iPort2ReadLen As Integer
Private Sub Command1_Click()
iPort2ReadLen = 34
rt = TestDLL(iPort2ReadLen)
MsgBox iPort2ReadLen
End SubiPort2ReadLen 作为全局变量,关闭VB窗体时“报错”。
测试二:Private Sub Command1_Click()
Dim iPort2ReadLen As Integer
iPort2ReadLen = 34
rt = TestDLL(iPort2ReadLen)
MsgBox iPort2ReadLen
End SubiPort2ReadLen 作为局部变量,关闭VB窗体时“不报错”。似乎和我猜想的近似,全局变量时,最后VB才释放iPort2ReadLen,可能因为和DLL释放次序等原因导致“出错”;局部变量时,早早就释放了,反而“不报错”得好好思考思考了,那个全局变量还得用的 :(