【发布时间】:2019-04-11 19:04:25
【问题描述】:
我有一个需要在 Python 中执行的 Simulink 模型。我一直在使用 NI VeriStand 生成的 C 代码来编译一个 Linux 共享库,它允许我在 Python 中执行我的模拟。
我想做的一件事是保存我的模拟状态(即连续和离散变量,以及时钟滴答声)。 VeriStand 导出的 C 源代码为此提供了一个名为 NIRT_GetSimState 的函数。
DLL_EXPORT int32_t NIRT_GetSimState(int32_t* numContStates, char * contStatesNames, double* contStates, int32_t* numDiscStates, char
* discStatesNames, double* discStates, int32_t* numClockTicks, char
* clockTicksNames, int32_t* clockTicks)
{
int32_t count = 0;
int32_t idx = 0;
if ((numContStates != NULL) && (numDiscStates != NULL) && (numClockTicks !=
NULL)) {
if (*numContStates < 0 || *numDiscStates < 0 || *numClockTicks < 0) {
*numContStates = 1;
*numDiscStates = 0;
*numClockTicks = NUMST - TID01EQ;
return NI_OK;
}
}
if ((contStates != NULL) && (contStatesNames != NULL)) {
idx = 0;
contStates[idx] = NIRT_GetValueByDataType(&(electric_motor_X.speed), 0, 0, 0);
strcpy(contStatesNames + (idx++ * 100), "speed");
}
if ((clockTicks != NULL) && (clockTicksNames != NULL)) {
clockTicks[0] = S->Timing.clockTick0;
strcpy(clockTicksNames, "clockTick0");
}
UNUSED_PARAMETER(count);
UNUSED_PARAMETER(idx);
return NI_OK;
}
我一直在尝试找到一种在 Python 中使用此函数的方法,就像从共享库中加载的那样。
from ctypes import *
self._model = CDLL(model_lib)
self._lib_get_state = self._model.NIRT_GetSimState
我想找到一种方法将正确的数据类型传递给 Python 中的函数。据我了解,我需要将指针传递给整数和数组。
我正在使用以下功能进行测试。我正在使用 ctypes 创建变量和数组。
def _get_state(self):
numContStates = c_int(-999)
contStatesNames = (c_wchar_p*1)('a')
contStates = (c_double*1)(-999.99)
numDiscStates = c_int(-999)
discStatesNames = (c_wchar_p*1)('a')
discStates = (c_double*1)(-999.99)
numClockTicks = c_int(-999)
clockTicksNames = (c_wchar_p*1)('a')
clockTicks = (c_int*1)(-999)
self._lib_get_state(byref(numContStates), byref(contStatesNames), byref(contStates), byref(numDiscStates), byref(discStatesNames),
byref(discStates), byref(numClockTicks), byref(clockTicksNames), byref(clockTicks))
print('Number of continuous states: ', numContStates.value)
print('Number of discrete states: ', numDiscStates.value)
print('Number of clock ticks: ', numClockTicks.value)
print('Names of continuous states: ', list(contStatesNames)) # Expecting ['speed']
print('Values of continuous states: ', list(contStates)) # Expecting [0.0]
我似乎得到了离散和连续状态数量的正确值,但是具有连续状态及其名称的数组没有更新。这是函数打印的内容:
Number of continuous states: 1
Number of discrete states: 0
Number of clock ticks: 1
Names of continuous states: ['a']
Values of continuous states: [-999.99]
所以,我们可以看到函数调用没有更新数组。我认为我可能没有使用正确的数据类型来调用该函数。这是我第一次使用 ctypes。
有人可以确认数据类型是否有错误吗?正确的语法应该是什么?
谢谢。
【问题讨论】: