将PJSIP的Python扩展从Python 2.4升级到Python 3.2

2014-11-24 09:56:42 · 作者: · 浏览: 0

Pjsip 1.8.5中python部分是基于python2.4的,这个有点跟不上时代了。


我的python环境是python3.2的。


修改步骤:


一 替换_pjsua.h和_pjsua.c中的函数
原来pjsip工程中python_pjsua的代码中大量试用了python2.*中stringobject.*的函数。这个string在python3以后已经完全被unicode string取代了,stringobject.h也被去掉了。所以需要将原有对python sting 的调用都替换为python Unicode string。Intobject也被longobject取代。


intobject -> longobject


stringobject -> unicodeobject


1. PyString_Size –> PyUnicode_GetSize


2. PyString_AsString -> PyUnicode_AsString


3. PyInt_AsLong -> PyLong_AsLong


4. PyString_Check -> PyUnicode_Check


5. PyString_AsString -> _PyUnicode_AsString


去掉ob_type相关行。


二 修改_pjsua.c文件中init_pjsua函数
1. 将原有:


/*


* Mapping C structs from and to Python objects & initializing object


*/


DL_EXPORT(void)


init_pjsua(void)


{


PyObject* m = NULL;


替换为:


/*


* Mapping C structs from and to Python objects & initializing object


*/


//DL_EXPORT(void)


PyMODINIT_FUNC


PyInit__pjsua(void)


{


PyObject* m;


2. 将原有的module初始化方式从:


m = Py_InitModule3(


"_pjsua", py_pjsua_methods, "PJSUA-lib module for python"


);


替换为:


m = PyModule_Create(&_pjsuamodule);


if (!m)


return NULL;


并要声明一个新的PyModuleDef结构_pjsuamodule


static const char module_docs[] =


"Create and manipulate C compatible data types in Python.";


static struct PyModuleDef _pjsuamodule = {


PyModuleDef_HEAD_INIT,


"_pjsua",


module_docs,


-1,


py_pjsua_methods,


NULL,


NULL,


NULL,


NULL


};


3. 增加返回值


PyMODINIT_FUNC有返回值


return m;


异常时返回NULL


4. 修改


PyTypeObject 的类型也不同:


PyObject_HEAD_INIT


将类似


static PyTypeObject PyTyp_pjsip_cred_info =


{


PyObject_HEAD_INIT(NULL)


0,


。。。


全部替换为


static PyTypeObject PyTyp_pjsip_cred_info =


{


PyVarObject_HEAD_INIT(NULL, 0)


三 修改setup-vc.py
将其中print相关修改


参考下面代码:


Old: print "The answer is", 2*2


New: print("The answer is", 2*2)


Old: print x, # Trailing comma suppresses newline


New: print(x, end=" ") # Appends a space instead of a newline


Old: print # Prints a newline


New: print() # You must call the function!


Old: print >>sys.stderr, "fatal error"


New: print("fatal error", file=sys.stderr)


Old: print (x, y) # prints repr((x, y))


New: print((x, y)) # Not the same as print(x, y)!


四 修改pjsua.py
上面的修改主要针对生成的_pjsua模块,实际上pjsip在python中注册了两个模块(_pjsua和pjsua),pjsua.py就是基于_pjsua的进一步封装的库,这个文件也需要修改。


1 将import thread去掉


# thread.start_new(_worker_thread_main, (0,))


threading.Thread(target=_worker_thread_main, args=(0,))


2 修改Error类声明:class Error(BaseException):


五 生成python库文件
执行setup-vc.py:


Python setup-vc.py install


在python中测试:


>>>import _pjsua


>>>import pjsua