gpt4 book ai didi

c++ - 关闭 pjsip 应用程序的正确方法是什么?

转载 作者:太空宇宙 更新时间:2023-11-04 11:29:35 25 4
gpt4 key购买 nike

我基于 pjsip (pjsua2) 编写了简单的应用程序。如果我在有事件调用时关闭我的应用程序,我在 Endpoint::on_call_state(pjsua_call_id call_id, pjsip_event *e) 中出现内存访问错误

我在关闭之前尝试做

Endpoint::instance().hangupAllCalls();
pj_thread_sleep(2000);

有时 2 秒的时间足以关闭应用程序并正确关闭,但有时则不然。

关闭 pjsua2 应用程序的正确方法是什么?怎么等什么电话都挂断了?

最佳答案

根据我使用 PJSUA2 的经验,退出的正确方法是确保在 pj::Account 析构函数之前调用所有调用的析构函数,并且在 pj::Endpoint 析构函数之前调用 pj::Account 的析构函数。

在我的应用程序中,我在 pj::Account 派生类中有整数调用计数器和退出 bool 标志,例如:

class MyAccount : public pj::Account
{
public:
...
void incrementCallsCount() { ++_callsCount; }
void decrementCallsCount() { --_callsCount; }
size_t getCallsCount() const { return _callsCount; }
...
void setWantExit(boot wantExitFlag) { _wantExitFlag = wantExitFlag; }
void onIncomingCall(pj::OnIncomingCallParam &prm)
{
if (_wantExitFlag)
return;
MyCall *call = MyCall::create(*this, prm.callId);
// Do your stuff with call:
// - add to map id->call
// - answer SIP 180 Ringing / SIP 200 OK
}
...
private:
std::atomic<size_t> _callsCount;
bool _wantExitFlag;
};

在 pj::Call 派生类的构造函数中,我调用了 incrementCallsCount(),在析构函数中,我调用了 decrementCallsCount(),如下所示:

class MyCall : public pj::Call
{
public:
typedef pj::Call base_class;
static MyCall *create(MyAccount &account, int callId)
{
return new MyCall(account, callId);
}

virtual void onCallState(pj::OnCallStateParam& prm)
{
pj::CallInfo ci = getInfo();
if (ci.state == PJSIP_INV_STATE_DISCONNECTED)
{
// You may call some onDisconnected() handler function here
delete this;
return;
}
}
...
private:
MyCall(MyAccount &account, int callId)
: base_class(account, callId)
, _myAccount(account)
{
_myAccount.incrementCallsCount();
}

virtual ~MyCall()
{
_myAccount.decrementCallsCount();
}

MyAccount &_myAccount;
};

注意构造函数和析构函数声明为私有(private)的,以确保用户只能通过静态函数 MyCall::create() 创建调用! MyCall 类负责内存管理:仅当 PJSUA2 要求删除调用时调用才被删除(PJSIP_INV_STATE_DISCONNECTED 调用状态)。

考虑到这些函数和类,如果您只想立即退出应用程序,您应该:

  • 通过 _myAccount.setWantExit(true) 停止在 MyAccount 中创建 MyCall。当 pj::Call::onIncomingCall() 函数立即返回时,PJSUA2 通过立即为调用执行 hangup() 来处理此问题。

  • 调用 Endpoint::instance().hangupAllCalls()

  • 等待 MyAccount::getCallsCount() 返回 0

  • 确保在 Enpoint 的析构函数之前调用 MyAccount 的析构函数

  • 退出申请

关于c++ - 关闭 pjsip 应用程序的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25325280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com