用C++寫python module
做這個小實驗的當天看到這個梗圖,相當呼應這個主題:
其它的程式語言對你作力學是沒用的,作計算就三本柱 Python、C++、Fortran 足矣,連 C 都沒什麼用處。
Python在計算的速度上相較於C++非常的緩慢,這個demo很清楚地呈現了這件事。
以計算力學為題,python在tool的開發,input的整合上具有優勢,但是在計算效能上的表現不佳,於是就有了許多與python互相支援的foreign function interface(FFI),如 swig, cython, pybind11。截python所長,補C++所短 (or vice versa) ,似乎是做出更好的力學程式不可或缺的元素,pybind扮演的角色於是顯現。接下來就簡單用C++寫一個python的module:
寫 .cpp/.h file
1 |
|
寫 CMakeList.txt
1 | cmake_minimum_required(VERSION 3.4) |
Build the module
1 | mkdir build |
在python中使用前面所建立的module
1 | ~/git-repo/importation/test$ python3 |
- dir(test)中可以看我們define的function以及attributes。
Problem Unsolved
- What’s the cause of success within
~/git-repo/importation/test
but not~/git-repo/importation
?1
2
3>>> import test
>>> dir(test)
['builtins', 'cached', 'doc', 'file', 'loader', 'name', 'package', 'path', 'spec']