我已经阅读了大量关于这个主题的资料,但在思考如何实现这一点时遇到了很多麻烦。
我想做的是有一个功能:
int Add(int a, int b) { return a + b; }
并且能够从我的 Python 脚本中调用它。我该怎么做呢?
最佳答案
到目前为止,最简单的方法是使用 ctypes 模块,它允许您直接从 Python 调用 C 库中的函数。一旦将 C 函数编译为库,就可以编写一些具有以下效果的内容:
# Load ctypes, and your library
from ctypes import *
mylib = CDLL("mylibrary.so")
# Declare the function's prototype. This isn't strictly required.
mylib.Add.argtypes = [c_int, c_int]
mylib.Add.restype = c_int
# Call it!
result = mylib.Add(123, 456)
关于python - 如何用 C 扩展 Python?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6961204/