python - 使用 ctypes 传递引用地址结构
问题描述
我的目标是提供ECG_sample (integer)
结构的和引用作为 C 代码的输入,并为其创建一个 python 包装器。以下是我尝试过的。该结构HRV_index
实际上有 5 个成员(4 个浮点数和 1 个整数),但我只为一个成员尝试代码。
gcc -c -Wall -Werror -fpic test.c
gcc -shared test.o -o test.so
创建共享库
C代码:
void simple_function(int16_t ecg_wave_sample,HRV_index *HRV)
{
Filter_CurrentECG_sample(&ecg_wave_sample, &ecg_filterout); // filter out the line noise @40Hz cutoff 161 order
Calculate_HeartRate(ecg_filterout,&global_HeartRate,&npeakflag); // calculate
if(npeakflag == 1)
{
read_send_data(global_HeartRate,*HRV);
printf("NN50: %d\n",HRV->nn50);
}
}
蟒蛇代码:
def wrap_function(lib, funcname, restype, argtypes):
''' Simplify wrapping ctypes functions '''
func = lib.__getattr__(funcname)
func.restype = restype
func.argtypes = argtypes
return func
class HRV_index(ctypes.Structure):
#_fields_ = [('mean', ctypes.c_float), ('sdnn', ctypes.c_float),('nn50', ctypes.c_int), ('pnn50', ctypes.c_float),('rmssd', ctypes.c_float)]
_fields_ = [('nn50', ctypes.c_int)]
def __repr__(self):
return '({0})'.format( self.nn50)
if __name__ == '__main__':
# load the shared library into c types. NOTE: don't use a hard-coded path in production code, please
libc = ctypes.CDLL("./test.so")
record = wfdb.rdrecord("/home/yasaswini/hp2-notebooks/notebooks/Algorithm_testing_on_database/MIT-BIH/100", channels=[0],sampto = 1000)
ECG_samples = record.p_signal[:,0]
ECG_samples = ECG_samples * 1000
Heart_rate_array = np.zeros(len(ECG_samples),dtype = np.int32)
print("Pass by reference")
simple_function = wrap_function(libc, 'simple_function', None, [ctypes.c_int,ctypes.POINTER(HRV_index)])
a = HRV_index(0)
print("Point in python is", a)
for i in range(len(ECG_samples)):
simple_function(ECG_samples[i], a)
print("Point in python is", a)
print()
我收到此错误:
Pass by reference
Point in python is (0)
Traceback (most recent call last):
File "/home/yasaswini/hp2-notebooks/notebooks/Algorithm_testing_on_database /structure_python_wrapper/test.py", line 45, in <module>
simple_function(ECG_samples[i], a)
ctypes.ArgumentError: argument 1: <class 'TypeError'>: wrong type
是ECG_sample[i]
整数,为什么会显示wrong type
错误?
解决方案
推荐阅读
- python - 列出所有元素,但只列出重复元素之一?
- amazon-web-services - Lambda 函数自定义域
- python - 如何在几分钟内计算列表中python中10个或更多unix时间戳之间的差异并将它们平均
- python - 重复特定行的熊猫数据框
- javascript - 限制复选框并在 2 个活动输入字段之间进行计算
- javascript - Javascript 正则表达式 - 在获取任何字符后在开头包含特定单词,直到某个字符出现
- c - 如何在c中打印而不跳转到文本末尾?
- java - 我想从副本中为我的 PHP 代码提供安全性
- c# - 如何保护可执行文件免受版本信息更改?
- c++ - C++ 隐式构造函数转换后跟类型向上转换