Python提供了多种方式来调用C语言代码,以便在Python程序中使用C语言的功能和性能优势。以下是几种常见的方法:
示例代码:
import ctypes
lib = ctypes.CDLL("libexample.so")
lib.add.argtypes = (ctypes.c_int, ctypes.c_int)
lib.add.restype = ctypes.c_int
result = lib.add(1, 2)
print(result)
示例代码:
cdef extern from "example.h":
int add(int a, int b)
def py_add(int a, int b):
return add(a, b)
示例代码:
%module example
%{
#include "example.h"
%}
int add(int a, int b);
import example
result = example.add(1, 2)
print(result)
以上是Python调用C的几种常见方法,根据具体需求和场景选择合适的方法。
领取专属 10元无门槛券
手把手带您无忧上云