CMake--C++代码打成.so包
1. 借助CMake打.so包
把目录utils下的文件打出.so包。

其中CMakeLists.txt内容:
cmake_minimum_required(VERSION 2.8)
aux_source_directory(. utils_src)
add_library(utils SHARED ${utils_src})
set_target_properties(utils PROPERTIES output_name "utils")
注意:前面的关键字可以大写也可以小写,括号内的关键字必须大写。
编译:
cmake .
make
生成了共享库libutils.so
2. 编译实际的项目
项目sticker_me中文件结构如下,其中build目录用于生成编译的结果。
它们之间的调用关系如下:
各个CMakeLists.txt如下:
./CMakeLists.txt:
cmake_minimum_required(VERSION 2.8)
project(sticker_me)
add_subdirectory(src)
add_subdirectory(facedetect)
add_subdirectory(utils)
src/CMakeLists.txt:
find_package(OpenCV REQUIRED)
include_directories(facedetect utils)
aux_source_directory(. src_dir)
add_executable(sticker_me ${src_dir})
target_link_libraries(sticker_me ${OpenCV_LIBS} utils facedetect)
facedetect/CMakeLists.txt:
include_directories(utils)
aux_source_directory(. facedetect_dir)
add_library(facedetect SHARED? ${facedetect_dir})
set_target_properties(facedetect PROPERTIES output_name "facedetect")
target_link_libraries(facedetect utils)
utils/CMakeLists.txt:
aux_source_directory(. utils_dir)
add_library(utils SHARED ${utils_dir})
set_target_properties(utils PROPERTIES output_name "utils")
编译项目打包成so文件
编译:
cd build
cmake ..
make
cython将py文件编译成so文件
一、环境准备
安装cython,以及gcc编译环境
wget https://bootstrap.pypa.io/get-pip.py
python get-pip.py
pip install cython
yum install -y gcc python-devel
二、编写测试脚本
test.py,内容如下
import os
def test():
print os.path.realpath('.')
三、将其拷贝到python系统路径
/usr/lib/python2.7/site-packages/test
在test目录下创建__init__.py, 与 test.py 的文件
test.py 上面内容如上所示
四、脚本测试
python
>>> import lyh.test
>>> lyh.test.test()
五、编译so文件
以下操作均在 /usr/lib/python2.7/site-packages/test 路径下执行
1. cython test.py
2. gcc -c -fPIC -I/usr/include/python2.7/ test.c
3. gcc -shared test.o -o test.so
六、验证so文件的可用性
1. 移除/usr/lib/python2.7/site-packages/test/test.py 文件,只保留 test.so文件
test
├── __init__.py
└── test.so
2.
python
>>> import test.test
>>> test.test.test()
可以执行
验证完成
七、使用setup.py 编译so
1. 编写setup.py文件,位于/usr/lib/python2.7/site-packages/test,内容如下:
from distutils.core import setup
from Cython.Build import cythonize
setup(
ext_modules = cythonize("test.py")
)
2.然后运行
setup.py build_ext --inplace
Python调用C++的.so文件
from ctypes import *
test = cdll.LodayLibrary(" ./certificate.so ")
print test
testpy = test.loadFile //loadFile是C++函数
testpy.argtype = c_char_p //这里是testy.argtype而不是testy..argtypes
testpy.restype = c_char_p
ss = "/systemInfo.sys" // 向 loadFile传的参数
params = testpy(ss)
print params
这里是testy.argtype而不是testy..argtypes,当参数多于2个时才用argtypes,例如:encodeFile.argtypes = [c_char_p, c_char_p]