cython 使用自定义C库中的函数
示例
我们有一个名为C的库my_random,可从自定义发行版生成随机数。它提供了两个我们要使用的功能:set_seed(longseed)和rand()(还有很多我们不需要的功能)。为了在Cython中使用它们,我们需要
在.pxd文件中定义一个接口,然后
调用.pyx文件中的函数。
码
test_extern.pxd
# extern blocks define interfaces for Cython to C code
cdef extern from "my_random.h":
double rand()
void c_set_seed "set_seed" (long seed) # rename C version of set_seed to c_set_seed to avoid naming conflicttest_extern.pyx
def set_seed (long seed):
"""Pass the seed on to the c version of set_seed in my_random."""
c_set_seed(seed)
cpdef get_successes (int x, double threshold):
"""Create a list with x results of rand <= threshold
Use the custom rand function from my_random.
"""
cdef:
list successes = []
int i
for i in range(x):
if rand() <= threshold:
successes.append(True)
else:
successes.append(False)
return successes
热门推荐
10 感谢韩语老师祝福语简短
11 升职文案高级祝福语简短
12 花童结婚祝福语大全简短
13 向国庆送祝福语简短
14 什么寄语简短祝福语女生
15 客户回礼祝福语大全简短
16 女孩生日祝福语简短创意
17 家长回复节日祝福语简短
18 给外婆敬酒祝福语简短