简体   繁体   English

在C中仅实现Python类的一部分

[英]Implementing only part of a Python class in C

I have a python class that has a couple performance-sensitive methods that justify being implemented in C. But it also has some methods that don't need to be fast and that would be a giant pain to write in C. 我有一个python类,它具有几个对性能敏感的方法,这些方法证明可以在C中实现。但是它也有一些不需要快速的方法,用C编写会很痛苦。

Is there a standard way to have the best of both worlds, where a few core methods are defined in C but some convenience methods are defined in python? 有没有一种标准的方法可以兼得两全其美,在C中定义了一些核心方法,而在python中定义了一些便捷方法?

(Ideally it should work for special methods like __str__ .) (理想情况下,它应该适用于__str__类的特殊方法。)

For example, maybe I could use inheritance. 例如,也许我可以使用继承。 Is that the right way to do it? 这是正确的方法吗? Are there performance costs? 有绩效成本吗?

If the C code doesn't need to interact with the object itself, possibly you could use the ctypes module to call C functions from your python code. 如果C代码不需要与对象本身进行交互,则可以使用ctypes模块从python代码中调用C函数。

Put your C code in into a shared library or DLL and then call it from your method. 将您的C代码放入共享库或DLL中,然后从您的方法中调用它。

Try Cython . 尝试Cython It really does a fantastic job blending the best features of both languages. 融合了两种语言的最佳功能,这确实做得很棒。 No longer do you have to decide between control and performance, and efficiency and ease of development. 您不再需要在控制和性能,效率和易于开发之间做出选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM