我有一个用C写的DLL,我必须使用它。这是可以的,但在一个地方我得到了一个错误。
int getHourTime()
{
struct tm *psttm;
time_t timet = //is initialzed correctly
psttm = localtime(&timet);
int nHour = psttm->tm_hour;
return nHour;
}我使用DLLImport在C#中调用它。当转到行:“psttm->tm_ or”时,我得到一个错误(抛出):“试图读取或写入受保护的内存”。我知道这是因为它返回了一个指向struct tm内部位置的指针,但是我该如何解决这个问题呢?
谢谢
发布于 2010-01-22 00:39:02
问题是因为下一行:
struct tm *psttm;
它未初始化为NULL。
发布于 2010-01-07 21:54:24
我不太确定这种情况下发生了什么,因为localtime返回了一个指向静态分配内存的指针。Very Bad Things(tm)必须处于运行状态,localtime才能返回错误指针。现在,如果你的timet结构有错误的值,MSDN声明将返回一个NULL值。
我认为你的应用程序中的内存已经被丢弃了。
执行以下工作:
int getHourTime()
{
struct tm *psttm = NULL;
time_t timet;
time(&timet);
psttm = localtime(&timet);
int nHour = psttm->tm_hour;
return nHour;
}发布于 2010-01-07 22:01:41
int getHourTime()
{
struct tm *psttm;
time_t timet = //is initialzed coorectly
// what is psstm? Set a breakpoint on this line and look at it
// before and after executing localtime()
psttm = localtime(&timet);
// if it's non-null then you can also do this:
#if _DEBUG
if (!HeapValidate(GetProcessHeap(), HEAP_NO_SERIALIZE, psttm)) {
puts("bad ptr in getHourTime");
}
#endif
int nHour = psttm->tm_hour;
return nHour;
}https://stackoverflow.com/questions/2020715
复制相似问题