【问题标题】:Passing Int as void* then getting the value将 Int 作为 void* 传递,然后获取值
【发布时间】:2010-12-12 15:20:12
【问题描述】:

我正在使用一个 Timer 类,该类将 void* 作为可选参数传递给回调。我需要传递一个整数,但我的逻辑似乎不太好。

在 Event_PlayerSpawn() 中,我有一个 int* clientIndex 指向 int“客户端”的内存位置。我将它传递给 void* 参数,然后在回调中将其再次转换为 int*,然后取消引用它以获取值。我到底哪里错了?

ResultType PlayerSpawnTimer::OnTimer(ITimer *pTimer, void *pData)
{
    int client = *((int*)pData);
    ConquestPlayer *pPlayer = dynamic_cast<ConquestPlayer*>(CEntity::Instance(client));

    Msg("Spawn Timer Called client = %d!\n", client);
    if(pPlayer)
    {
        pPlayer->FindSpawnLocation();
    }

    return Pl_Continue;
}

void GameManager::Event_PlayerSpawn(IGameEvent *event)
{
    int client = engine->IndexOfEdict(GetEdictOfUserID(event->GetInt("userid")));

    int *clientIndex = &client;
    // Add a 0.1 second delay then handle spawn location
    timerPlayerSpawn = timersys->CreateTimer(&playerSpawnTimerCallback, 5.0, clientIndex, 0);
}

【问题讨论】:

  • 您能说得更具体些吗?你有编译错误吗?那么错误信息是什么,你在哪一行呢?还是运行时错误?
  • 运行时错误,在回调中输出为0,但传递时不同(运行时变化,但在1-33之间)。

标签: c++ pointers void-pointers


【解决方案1】:

尝试以下方法:

timerPlayerSpawn = timersys->CreateTimer(&playerSpawnTimerCallback, 5.0,(void *) client, 0);

在回调中:

int client = (int)pData;

【讨论】:

    【解决方案2】:

    我对 timersys->CreateTimer 实现了解不多,但“int client”是 Event_PlayerSpawn 的本地,并且可能在调用 PlayerSpawnTimer::OnTimer 时被释放。

    如果您确实需要传递 void * 而不是 int,则可能需要使用“new”和“delete”来确保“int client”的内存得到正确分配和释放。

    【讨论】:

      【解决方案3】:

      您需要为变量分配内存。但是现在它在堆栈中并在您离开 Event_PlayerSpawn 时被销毁。

      int *clientIndex = new int[1];
      clientIndex[0] = client;
      

      【讨论】:

      • 不需要为此创建一个数组:new int(client) 可以正常工作。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-23
      • 1970-01-01
      • 2020-12-05
      • 1970-01-01
      • 2019-04-25
      • 1970-01-01
      相关资源
      最近更新 更多