[英]Calculating entropy in Python using a C function with ctypes
I am trying to use a C function to calculate the Sahnnon entropy within a Python script, using the ctypes library.我正在尝试使用 C function 使用 ctypes 库计算 Python 脚本中的 Sahnnon 熵。
I have consulted some tutorials, and according to what I understood, the C code can be something like this (I called "entropy.c":我查阅了一些教程,据我了解,C代码可以是这样的(我叫“entropy.c”:
#include <math.h>
#include <stdio.h>
float entropy(float *p, int n)
{
int i;
float ent;
ent = 0.0;
for(i=0; i< n; i++)
{
if(p[i] > 0.0)
{
ent += -p[i] * (double) log( (double) p[i]);
}
}
return ent;
}
In the C code, there is a variable array (p) that represents the distribution to which the entropy must be calculated.在 C 代码中,有一个变量数组 (p) 表示必须计算熵的分布。
Now I have converted this to a "shared object" file in the usual way:现在我以通常的方式将其转换为“共享对象”文件:
$ gcc -fPIC -shared -o entropy.so entropy.c
So from my understanding, the code in Python would have to look something like this:因此,据我了解,Python 中的代码必须如下所示:
import ctypes
so_file="./entropy.so"
entropy=ctypes.CDLL(so_file)
n=ctypes.c_int(2)
p=(ctypes.c_float * 2)(0.25,0.75)
print(entropy.entropy(p,n))
However, regardless of p, I always get as a result:但是,无论 p 是什么,我总是得到以下结果:
$ python entropy.py
$ 2
I have tried to find a solution but could not find it.我试图找到解决方案,但找不到。 So the question is what am I doing wrong here?
所以问题是我在这里做错了什么?
Thanks for any help.谢谢你的帮助。
You didn't tell Python the return type, so it guessed that it was int
, wrongly, and thus read the return value from the wrong place (assuming you're on x86-64, it read from eax
instead of xmm0
) and interpreted it wrongly.您没有告诉 Python 返回类型,所以它猜测它是
int
,错误地,因此从错误的位置读取返回值(假设您在 x86-64 上,它从eax
而不是xmm0
)并解释它错了。 Do entropy.entropy.restype = ctypes.c_float
before print(entropy.entropy(p,n))
.在
print(entropy.entropy(p,n))
之前执行entropy.entropy.restype = ctypes.c_float
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.