Python调用PJSUA2的utilAddPendingJob方法遇类型错误求助
Fixing TypeError with
utilAddPendingJob in PJSUA2 Python Bindings Let's break down what's causing that TypeError and fix it step by step:
The Root Causes
Your issue stems from three key problems in your code and how SWIG handles C++ abstract classes in Python:
- Missing parent class initialization: Even though
pj.PendingJobis marked as abstract by SWIG, your subclass needs to initialize the underlying C++ object by calling the parent constructor. Without this, SWIG can't wrap your Python object into a validpj::PendingJob*pointer. - Mismatched method signature: The
executemethod in your subclass doesn't match the exact signature of the pure virtual function in the C++PendingJobclass. SWIG relies on exact signature matches to recognize valid implementations of abstract methods. - Invalid variable reference: You're trying to print
textdirectly instead of accessing the instance variable withself.text(this would cause aNameErroronce the type issue is fixed).
Fixed Code
Here's the corrected version of your code:
import pjsua2 as pj class MyJob(pj.PendingJob): def __init__(self, text): # Initialize the parent class to create the underlying C++ object super().__init__() self.text = text # Exact match for the C++ method signature: no default parameters def execute(self, is_pending): print(self.text) # Usage remains the same job = MyJob("test") pj.Endpoint.instance().utilAddPendingJob(job)
Explanation
- Parent constructor call: The
super().__init__()line might seem counterintuitive since SWIG'sPendingJob.__init__raises an error, but this is part of SWIG's abstraction layer. Calling it ensures the underlying C++PendingJobinstance is created, which is required for SWIG to convert your Python object to a valid C++ pointer. - Signature consistency: The C++
PendingJob::executeexpects a single boolean parameter with no default value. Removing theis_pending = Falsedefault in your Python method ensures SWIG recognizes it as a valid implementation of the pure virtual function. - Instance variable access: Using
self.textcorrectly references the instance variable you initialized in__init__, avoiding aNameErrorwhen the job executes.
SWIG handles abstract C++ classes in Python by requiring strict adherence to method signatures and proper initialization of parent classes. Fixing these points will resolve the type mismatch and let your pending job execute as expected.
内容的提问来源于stack exchange,提问作者Rob
相关产品推荐
相关产品推荐

