Python 使用ctypes传递引用地址结构

Python 使用ctypes传递引用地址结构,python,ctypes,Python,Ctypes,我的目标是给出一个ECG_示例(整数)和该结构的引用作为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_C

我的目标是给出一个
ECG_示例(整数)
和该结构的引用作为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);
    }
}
python代码:

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
按引用传递
python中的点是(0)
回溯(最近一次呼叫最后一次):
文件“/home/yasaswini/hp2 notebooks/notebooks/Algorithm\u testing\u on\u database/structure\u python\u wrapper/test.py”,第45行,in
简单_函数(ECG_样本[i],a)
ctypes.ArgumentError:参数1::错误类型

ECG\u sample[i]
是一个整数,为什么它显示
错误类型
错误?

在引发异常的lint之前打印(type(ECG\u samples[i]),ECG\u samples[i])
并更新输出。或者使用
简单函数(int(ECG\u samples[i]),a)
或者
简单函数(ctypes.c\u int16(ECG\u samples[i] ),a)
或可能
简单函数(ctypes.cast(ctypes.c\u int16,ECG\u样本[i]),a)