簡體   English   中英

SWIG 調用函數指針存儲在結構中

[英]SWIG call function pointers stored within struct

我有一個結構如下:

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,
};

星系_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,
};

這對我有用。 方案5是首選方案。

測試文件

%module test

%{
#include "test.h"
%}

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

%include "test.h"    

測試.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 是一個以函數指針為參數的函數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM