簡體   English   中英

使用 ctypes 將數組從 python 傳遞到 C,然后在 Python 中使用該數組

[英]Passing an array from python to C using ctypes, then using that array in Python

我正在嘗試histogram of Poisson random generated variables using Python and C 我想使用Python for plotting ,使用 C C for generating. This resulted in the following to codes C for generating. This resulted in the following to codes

Python:

import ctypes
import numpy as np
import matplotlib.pyplot as plt
import time

lam = 5.0
n = 1000000

def generate_poisson(lam, n):
    array = np.zeros(n, dtype= np.int)
    f = ctypes.CDLL('./generate_poisson.so').gen_poisson
    f(ctypes.c_double(lam), ctypes.c_int(n), ctypes.c_void_p(array.ctypes.data))
    return array

start_time = time.time()
array = generate_poisson(lam,n)
print(time.time() - start_time)

plt.hist(array, bins = [0,1,2,3,4,5,6,7,8,9,10,11,12], density = True)
plt.savefig('fig.png')
print(array)

C:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>

double get_random() { return ((double)rand() / (double)RAND_MAX); }

int poisson_random(double lam){
    int X;
    double prod, U, explam;

    explam = exp(-lam);
    X = 0;
    prod = 1.0;
    while (1){
        U = get_random();
        prod *= U;
        if (prod > explam){
            X+=1;
        }
        else {
            return X;
        }
    }
}

void gen_poisson(double lam, int n, void * arrayv)
{
    int * array = (int *) arrayv;
    int index = 0;
    srand(time(NULL));

    for (int i =0; i<n; i++, index++){
        //printf("before %d\n", array[i]);
        array[index++] = poisson_random(lam);
        //printf("after %d\n", array[i]);
    }
}

gen_poisson()的 for 循環內,理解為什么會這樣工作,或者至少它似乎能正常工作的問題。 以某種方式使用array[index++]而不是array[index]會產生正確的直方圖。 但我真的不明白為什么會這樣。 當 for 循環更改為時,代碼似乎也可以工作

for (int i =0; i<2*n; i++){
        //printf("before %d\n", array[i]);
        array[i++] = poisson_random(lam);
        //printf("after %d\n", array[i]);
}

有人可以解釋為什么在這種情況下循環必須遞增兩次嗎? 我剛開始在 C 編程,而我在 Python 有一些經驗。所以假設罪魁禍首是我對 C 缺乏了解。提前謝謝你

gen_poisson更改為:

void gen_poisson(double lam, int n, void * arrayv)
{
    long * array = (long *) arrayv;
    srand(time(NULL));
    for (int i =0; i<n; i++){
        array[i] = poisson_random(lam);
    }
}

解決了問題。 正如將數組聲明為int *而不是long *所指出的那樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM