1, 创建并编译C++程序
#include <fstream>
#include <assert.h>
#include <malloc.h>
#include <stdlib.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <iostream>
using namespace std;
extern "C" {
int load_data(void);
int FreeMem(void);
char* ExtMobileLocation(char* mobile);
。。。。。。
}
char* ExtMobileLocation(char* mobile)
{
return" ; ; ";
}
编译命令:g++ -c element_dec.cpp
g++ -fPIC -shared element_dec.cpp -o element_dec.so
2, python中调用
!/usr/bin/python
#coding=utf-8
from ctypes import *
import os
import sys
import time
#print os.getcwd() + '/id_dec.so'
pDll=cdll.LoadLibrary(os.getcwd() +'/element_dec.so')
pDll.load_data()#加载数据需消耗一定时间
strToBeDec = sys.stdin.readline()
typeK = sys.argv[1]
start = time.clock()
records = 0
while strToBeDec:
strKey = strToBeDec.replace("\n","").split("\t")[0]
#print strKey
iftypeK == "Mobile":#手机解析
pDll.ExtMobileLocation.restype =c_char_p
pDll.ExtMobileLocation2.restype =c_char_p
#printpDll.ExtMobileLocation(strKey).decode("gbk").encode("utf-8")
strDecResult = pDll.ExtMobileLocation2(strKey).decode("gbk").encode("utf-8")
strPro,strCity,strCode = strDecResult.split(";")[0:3]
print strPro+"\t"+strCity+"\t"+strCode
records+=1
strToBeDec = sys.stdin.readline()
end = time.clock()
print records," records run: %f s"% (end - start)
pDll.FreeMem()
运行示例:cat dec_test_data.txt |awk -F '\t''{print $13}'|./element_dec.py Mobile