首页 > 解决方案 > 使用 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错误?

标签: pythonctypes

解决方案


推荐阅读