存储在struct

时间:2015-09-25 22:40:30

标签: python c struct function-pointers swig

我有一个结构如下:

struct power_model {
    int64_t (*estimate_energy)(statistics *stats, statistics *scaled_stats, parameters *from, parameters *to, energy_container *energy_container);
    int64_t (*estimate_performance)(statistics *stats, parameters *params);
    uint32_t (*freq_to_volt)(uint32_t freq);
};

我的代码包含多种电源模型。 我想用SWIG包装这些模型并将它们暴露给Python,以便我可以运行我的单元测试。

虽然SWIG文档讨论了暴露函数指针,但它没有讨论结构中包含的函数指针。 我试图将调用封装在我的接口文件

%{
#include "models.h"
%}

%include "models.h"

%extend power_model {
  %pythoncallback;
  int64_t (*estimate_energy)(statistics *stats, statistics *scaled_stats, parameters *from, parameters *to, energy_container *energy_container);
  int64_t (*estimate_performance)(statistics *stats, parameters *params);
  uint32_t (*freq_to_volt)(uint32_t freq);
  %nopythoncallback;
}

我还尝试使用%constant为字段名称添加前缀。

通过这些方法,我总是会遇到同样的错误:

In [3]: model.estimate_energy()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-b2e3ace2fc9b> in <module>()
----> 1 model.estimate_energy()

TypeError: 'SwigPyObject' object is not callable

如何调用struct power_model中包含的函数指针引用的基础函数?

修改: 为了详细说明我的设置,我还提供了两个额外的文件,以便更好地解释我尝试使用power_model界面实现的设置。

nexus5.c

static int64_t estimate_energy(statistics *stats, statistics *scaled_stats, parameters *from, parameters *to, energy_container *energy) {
    ...
}
static int64_t estimate_performance(statistics *stats, parameters *params) {
    ...
}
static uint32_t freq_to_volt(uint32_t freq) {
    ...
}

struct power_model nexus5_power_model = {
     .estimate_energy = estimate_energy,
     .estimate_performance = estimate_performance,
     .freq_to_volt = freq_to_volt,
};

galaxy_s.c

static int64_t estimate_energy(statistics *stats, statistics *scaled_stats, parameters *from, parameters *to, energy_container *energy) {
    ...
}
static int64_t estimate_performance(statistics *stats, parameters *params) {
    ...
}
static uint32_t freq_to_volt(uint32_t freq) {
    ...
}

struct power_model galaxy_s_power_model = {
     .estimate_energy = estimate_energy,
     .estimate_performance = estimate_performance,
     .freq_to_volt = freq_to_volt,
};

1 个答案:

答案 0 :(得分:1)

这对我有用。解决方案5是首选解决方案。

test.i

%module test

%{
#include "test.h"
%}

// Solution 5 (right one)
%pythoncallback;
double f5(double);
%nopythoncallback;
%ignore f5;

%include "test.h"    

test.h

typedef double (*fptr_t)(double);

// Solution 5
double f5(double x) {
  return x*x;
}

typedef struct bla {
  fptr_t f;
} bla;

从Python中

import test
s = test.bla
# Assign function pointer
s.f = test.f5
# Execute
s.f(2)

f是一个将函数指针作为参数

的函数
相关问题