1. 程式人生 > >python中呼叫動態連結庫(C++,linux)

python中呼叫動態連結庫(C++,linux)

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