cython
Cコードを折り返す
サーチ…
カスタムCライブラリの関数の使用
カスタム分布から乱数を生成するmy_random
というCライブラリがあります。 set_seed(long seed)
とrand()
(そしてもっと多くの場合は必要ありません)の2つの関数を使いたいと思います。 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 conflict
test_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
Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow