1. 程式人生 > >編譯專案打包成so檔案

編譯專案打包成so檔案

CMake--C++程式碼打成.so包

1. 藉助CMake打.so包

 把目錄utils下的檔案打出.so包。

%hmqfua%60i

其中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目錄用於生成編譯的結果。

CMake簡介和使用示例 - 淮靜 - 淮靜的部落格

它們之間的呼叫關係如下:

CMake簡介和使用示例 - 淮靜 - 淮靜的部落格

各個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")

編譯:

cd build

cmake ..

make


一、環境準備

    安裝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]