Category Archives: Tech

Extending Python by reusing existing C++ codes


Extending Python by reusing existing C++ codes

Zhuotong Nan ([email protected])

Why I do this?

First let me show you some codes wrote in Python:

(code snippet)

This class is to call an external executable, which will generate necessary data files in a proper file format for further work. When I come to port this class to Windows, I found it is unable to work since os.fork and os.wait do not exist in Windows, and much more worse, os.execvp cannot run as expected. My initial solution is to look for their equivelant under Windows but hard to solve it in a fast way. The alternative choice is to implement Read_xmrg2 as an module of Python. Fortunately, we have c source codes of Read_xmrg2 (which can be found at http://www.weather.gov/oh/hrl/dmip/2/xmrgformat.html). I start to look for some information regarding this implementation.

Extending using SIP

This solution is conventionally called extending Python. But the common implementation presented by Python help is hard to do. More efforts should be placed in doing the conversion between C/C++ data types and Python’s. Since I have background on Qt, a helpful tool called SIP (http://www.riverbankcomputing.co.uk/sip/) draws my attention. There are a number of tools to do the Python bindings. Some studies shows SIP is easier to do such kind of bindings. Although SIP comes with a nice reference file, it is a little bit hard for a newbie to start.

Step 1 Tuning existing c codes

Since I prefer C++ style, I changed existing Read_xmrg2 codes to a C++ class. Following is its simple header file (dmip2.h).

  (code snippet)

Note reverse_byte_order and its short equivalent are used by read_xmrg2 functions. I made them private. Also I declared read_xmrg2 as static. Header file should be generated since SIP will link this header file to generate conversion codes. One work we remains is to convert main function in original c codes to a common function.

(code snippet)

Keep in mind, we should add DMIP2 as a domain prefixing to every method (read_xmrg, constructor, reverse_byte_order, etc). Next, I commented some codes since as a function there is no necessity to check argument number. Also comment declarations of functions reverse_byte_order and reverse_byte_order_short since we declare them in the class definition. Replace original argv[1] to variable fn. Note I also add a fflush(stdout) to force the print information to show immediately, otherwise the caller (Python function) also prints messeges which will mess up the console output.

Then, make the class compiled as a shared library (with extension as DLL). In Eclipse C++ dev, we only need to switch Artifact type to Shared Library as shown below (figure 2), and then compile codes to generate dmip2_py.dll.


figure 1. DLL building settings in Eclipse c++

Step 2 Generate Python module using SIP

2.1 Install SIP

Get SIP package (sip-4.7.1zip) from http://www.riverbankcomputing.co.uk/sip/. SIP supports all versions of Python since v2.3. Version 2.4 was installed in my computer because some other Python modules depend only this version. Unpack SIP zip file to a directory (sip-4.7.1) under Python v2.4 directory (generally c:Python24). Open command window, enter the directory SIP located, and then type "c:python25python configure.py -p win32-g++" which will configure SIP with MinGW compiler I installed in my environment. Default settings of configuration are suitable for most cases. After its configuration, type "mingw32-make" to compile and "mingw32-make install" to install SIP module with Python. More information is available in the reference file (sipref.html) under doc directory of SIP installtion directory.

2.2 Generate a SIP specification file

(code snippet)

Note here if the header file of the wrapped class is not at the same directory as the sip files (dmip2.sip), we should specify its relative location with #include directive. I save this specifation file in sip diectory (figure 2). Since we are only interested in read_xmrg2 function, this sip specification file exposes only this declaration. Change %Module on your demand. In Python codes, we can call read_xmrg2 by DMIP2PY.DMIP2.read_xmrg2() if we import this module.


figure 2. sip folder contains sip files, while src folder c++ header files as wells as source files.

 

2.3 Built a configure file for faciliating building module

(code snippet)

The line os.system(…) will enable generated files put the same folder as sip files. You should change dmip2.sip according your naming. Other point should be mentioned is makefile.extra_libs where specifies the name of DLL files produced in Step 1. If the DLL is in different location, make corresponding change to makefile.extra_lib_dirs. I prefer copying DLL file(s) (for ex. dmip2_py.dll) to sip directory.

Save to configure.py in the sip directory, run it by typing "python configure.py" in command window. Be sure you have set python location (for ex. c:python24) and MinGW binary location (for ex. c:mingwbin) to your system path variable. Otherwise please specify the absolute path here.

This compilation will produce some new files. See figure 3 for my case.


figure 3. The compilation will produce ultimate python module which wraps DLL functionality.

Step 3 Using generated Python module in Python codes

We need to make some changes to runProgram to employ generated Python module.

(code snippet)

Here we first import DMIP2PY module, and enhance the function by enabling it runs on varying operating system. Please note if we use import directive as shown in the above case, we have to locate the function by MODULENAME.CLASSNAME.FUNCTIONNAME(). But if we import functions by "from DMIP2PY import *", we can refer to the function by CLASSNAME.FUNCTIONNAME().

Do not forget to copy the compiled Python module (dmip2py.pyd) and associated DLL file (dmip2_py.dll) to the same directory as the calling python file.

Conclusion

We walked through how to extend python by using SIP step by step. It’s not much hard to implement your real application. Efforts should be made to the SIP specification file. More details can be found in the reference manual located in the doc directory of sip source package. But for simple scenarios, simply do enhancement based on the above example. SIP also have special design for Qt (www.trolltech.com) application. In this context, it is the unique choice for Qt users.

Sources codes can be availabe on request. Send your comments and suggestions to [email protected].

All rights reversed.

IF YOU ARE INTESTED IN COMPLETE VERSION, PLEASE SEND ME EMAIL OR REQUEST BY FOLLOWING COMMENTS.

Download PDF version (174KB)

Protector Suite 5.6.0 build 3152

The latest version of Protector Suite for SONY VAIO SZ series can work both
XP and Vista.
1. uninstall any previous version
2. reboot
3. download this versio from
http://dlsvr03.asus.com/pub/ASUS/nb/R1F/FingerPrint_Vista32bit_070126.zip
and install it.
4. reboot
I tested it on my XP sp2, works fine. This also supports both IE 6 (I don’t
know if it works with IE 7) and Firefox 2.0.x.

Ref: http://forum.notebookreview.com/showthread.php?t=101461

Gold Parser文本词法分析

在westdc的搜索输入字符串时用了一下Gold Parser,感觉真是个好东西,不过学起来有点费劲,花了我3天时间,才逐渐明白并动手做了一个比较简单的字串分析器。代码如下:

! GOLD Parser Builder
! Version 3.4.4
!
"Name" = "Simple search Grammer"
"Version" = "1.0"
"Author" = "Zhuotong Nan"

"Start Symbol" = <Query>

!—————–Sets
!Valid char for string keyword
{kw1} = {All Valid} – {Control Codes} – ["]

!Valid char for non-string keyword
{kw2} = {kw1} – {Whitespace} -[()]

!—————–Terminal

SimpleKw = {kw2}+
StringKw = ‘"’ {kw1}* ‘"’

!—————–Rules

<Keyword> ::= SimpleKw | StringKw

<Unit> ::= <Keyword>
| ‘(‘ <Query> ‘)’

<And> ::= <Query> <Unit>
| <Query> ‘and’ <Unit>

<Or> ::= <Query> ‘or’ <Unit>

<Query> ::= <And>
| <Or>
| <Unit>

支持 and, or查询,kw1 and kw2 可以省略为 kw1 kw2,支持括号优先级,支持""指定字串
通过CalithaLib engine连接到c#应用程序
语法并不复杂,但用于arcims的search_metadata比较别扭,如果将分析出来的keywords组织成arcims识别的search_metadata结构费了比较大的劲

中文搜索仍有问题,明天再检查,arcims是否有专门的设置没有。

User Control的呈现问题

如果自定义用户控件使用了List或其它集合属性,在vs 里的design view下呈现出错。
解决方法,在该属性上添加:
[System.ComponentModel.DesignerSerializationVisibility(
System.ComponentModel.DesignerSerializationVisibility.Content)]
而对于List,为了使用字符串集合,还可以添加:
[System.ComponentModel.Editor("System.Windows.Forms.Design.StringCollectionEditor, System.Design",
"System.Drawing.Design.UITypeEditor, System.Drawing")]

1) http://blogs.msdn.com/toub/archive/2004/10/12/241277.aspx

BUG in coolstorage ACCESS provider

它对access的支持还有一些bug,比如access不支持多个语句通过分号一起查询,在clone()时返回的是oledb provider等,需要自己做一些调整。不过这些问题对sql server不存在,估计作者没对access作专门的测试。

Bug in CoolStorage 1.1

Using the Access db provider, the constrcuted sql statement such as "select [ab.Descript] fad. [ab.UpdateDate] fae from [tblUpdate] ab" shows error. In my version of Access, the keyword "AS" between column name and alias name should exist.
Change CSDataProvider.cs source code fix this small problem.

 

CoolStorage.net

不错的ORM工具,可以将数据库很方便的映射到强类型对象。值得学习。
该作者同时还有一个asp.net framework,叫ProMesh.net,基于mvc结构来实现asp.net应用程序
请访问 codeplex获取最新版本

Umbraco v3.02 installation

I did not get installation guide for Umbraco v3 on xp sp2.

Current envir. Xp sp2 Chinese Version

1. Install IIS 5 using appwiz.cpl.
2. Config IIS default website to point to the dir where Umbraco v302 was located.
3. Download ASP 2.0 AJAX extension 1.0 from http://www.microsoft.com/downloads/details.aspx?FamilyID=ca9d90fa-e8c9-42e3-aa19-08e2c027f5d6&displaylang=en. Without this pre-quisite, exception saying requirement of System.Web.Extension will be prompted.
4. Correct a typo error at the line 28 in the /Install/default.aspx. (Text="Next ? -> Text="Next" )
5. Config the connection string (with the key "umbracoDbDSN") in the file web.config
6. do as the wizard goes.

DONE

 

P800时区同步问题

问题描述:ActiveSync同步后,P800上的时区会从北京时间自动换回太平洋时间GMT-8
解决方案:从网上下载补丁;或者将访问城市设成北京,据说也可以解决这个问题。

ASP session timeout on IIS 6

I have configurated several legacy ASP websites in my IIS 6 server, together
with new asp.net 2.0 application. For stability sake, a separate application
pool is built for those asp applications. However, we met the session state
loss problem when running these apps.

To address this problem,
1) disable the recycle time setting in application pool;
2) set timeout after idle to 20 mins;
3) make sure web garden to 1
This is only for in process mode. Out-of-process mode is not affected.

For the underlying mechanics, please refer to David’s blog at
http://blogs.msdn.com/david.wang/archive/2005/09/19/Why_do_I_lose_ASP_Sessio
n_State_on_IIS6.aspx