用 Python 包裝 C 庫:C、Cython 還是 ctypes? - Wrapping a C library in Python: C, Cython or ctypes?

問題:

I want to call a C library from a Python application.我想從 Python 應用程序調用 C 庫。 I don't want to wrap the whole API, only the functions and datatypes that are relevant to my case.我不想包裝整個 API,只包裝與我的案例相關的函數和數據類型。 As I see it, I have three choices:在我看來,我有三個選擇:

  1. Create an actual extension module in C. Probably overkill, and I'd also like to avoid the overhead of learning extension writing.在 C 中創建一個實際的擴展模塊。可能有點矯枉過正,而且我還想避免學習擴展編寫的開銷。
  2. Use Cython to expose the relevant parts from the C library to Python.使用Cython將 C 庫中的相關部分公開給 Python。
  3. Do the whole thing in Python, using ctypes to communicate with the external library.在 Python 中完成整個事情,使用ctypes與外部庫進行通信。

I'm not sure whether 2) or 3) is the better choice.我不確定 2) 還是 3) 是更好的選擇。 The advantage of 3) is that ctypes is part of the standard library, and the resulting code would be pure Python – although I'm not sure how big that advantage actually is. 3) 的優點是ctypes是標準庫的一部分,生成的代碼將是純 Python - 儘管我不確定這種優勢實際上有多大。

Are there more advantages / disadvantages with either choice?任何一種選擇都有更多的優點/缺點嗎? Which approach do you recommend?您推薦哪種方法?


Edit: Thanks for all your answers, they provide a good resource for anyone looking to do something similar.編輯:感謝您的所有回答,它們爲任何想做類似事情的人提供了很好的資源。 The decision, of course, is still to be made for the single case—there's no one "This is the right thing" sort of answer.當然,決定仍然是針對單個案例做出的——沒有人會給出“這是正確的事情”之類的答案。 For my own case, I'll probably go with ctypes, but I'm also looking forward to trying out Cython in some other project.對於我自己的情況,我可能會使用 ctypes,但我也期待在其他項目中嘗試使用 Cython。

With there being no single true answer, accepting one is somewhat arbitrary;由於沒有唯一的正確答案,接受一個有點武斷; I chose FogleBird's answer as it provides some good insight into ctypes and it currently also is the highest-voted answer.我選擇了 FogleBird 的答案,因爲它提供了對 ctypes 的一些很好的見解,而且它目前也是投票最高的答案。 However, I suggest to read all the answers to get a good overview.但是,我建議閱讀所有答案以獲得一個好的概述。

Thanks again.再次感謝。


解決方案:

參考一: https://en.stackoom.com/question/89HO
參考二: https://stackoom.com/question/89HO
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章