[英]Attach C method to existing Python class
我想知道是否可以在不使用 SWIG 或其他框架的情況下向 Python 類添加本機方法。
我深入研究了 Python C Api,但我沒有看到合適的方法。
我想我應該有一個 init 方法來加載現有模塊並向它添加一個方法:
PyMODINIT_FUNC
PyInit_lambert(void)
{
PyObject* m;
m = PyImport_ImportModule("lambert");
/* Some code to attach method */
return m;
}
有人可以給我一些提示嗎?
如果簡單性是一個優點,那么很難擊敗ctypes
模塊。 它允許您用 Python 而非 C 編寫 Python-C 接口。根據我的經驗,這比編寫 Python 擴展容易得多。 我想有一些開銷,所以如果將在內部循環中調用它,您可能會看到性能問題。
過去,我剛剛用 C 重寫了最內層的循環。
然后,您可以使用普通的舊 Python 進行子類化。
from some_module import SomeClass
import ctypes
my_c_func = do_the_ctypes_stuff() # see ctypes doc (linked above)
class WrappedClass(SomeClass):
def added_method(self, *args, **kwargs):
cargs = my_process_py_args(*args, **kwargs)
cret = my_c_func(*cargs)
my_apply_c_result(self, *cret)
return my_make_py_result(self, *cret)
我的建議是編寫普通的 Python 和普通的 C,不要試圖對界面太花哨。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.