操作环境:centos7
python版本:Python 2.7.5
gcc版本:gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-44)
python安装:https://www.runoob.com/python3/python3-install.html
生成.so动态库文件:g++ -o test.so -shared -fPIC test.cpp
c++代码(test.cpp):
#include <stdio.h>
extern "C"
{
int add(int a, int b)
{
return a + b;
}
void print_sum(unsigned long ulNum)
{
while (ulNum != 0)
{
printf("The ulNum is : %u\n", ulNum--);
}
}
}
python代码(test.py):
#-*-encoding:utf-8 -*-
from ctypes import *
import time
if __name__=='__main__':
time_begin=time.clock()
dll=CDLL('./test.so')
print(dll.add(5,7))
dll.print_sum(10000)
t=time.clock()-time_begin
编写代码结束后把test.py和test.so放在同一级目录下
执行python代码:python test.py