我有同样的问题。帮助我的是 MathWorks 提供的以下示例:
open('sldemo_sfun_counterbus.c')
open('counterbus.h')
以下是一些代码片段,展示了如何根据上面的示例获取 simulink 总线对象的信息:
// Defined localy, could also be defined in a header
typedef struct
{
uint32_t ui32_header_val;
double f64_header_val;
} YOURSTRUCT;
static void mdlInitializeSizes(SimStruct *S)
{
// ... your code
// Specify I/O
if (!ssSetNumInputPorts(S,1)) return;
//Bus inport
DTypeId dataTypeIdReg;
ssRegisterTypeFromNamedObject(S, "YOURBUS", &dataTypeIdReg);
ssSetInputPortDataType(S, 0, dataTypeIdReg);
ssSetBusInputAsStruct(S, 0, true);
ssSetInputPortOverWritable(S, 0, 1);
ssSetInputPortOptimOpts(S, 0, SS_REUSABLE_AND_LOCAL);
// This is important !!! Specifies that the signal elements entering the specified port must occupy contiguous areas of memory
ssSetInputPortRequiredContiguous(S, 0, 1);
// Configure the dwork (__dtBusInfo)
ssSetDWorkDataType(S, 0, SS_INT32);
ssSetDWorkUsageType(S, 0, SS_DWORK_USED_AS_DWORK);
ssSetDWorkName(S, 0, "dtBusInfo");
// This contains the offset and sizes of your struct
ssSetDWorkWidth(S, 0, 4);
// The DWorker needs a depth of 4, since it stores the size of each element and its offset
ssSetDWorkComplexSignal(S, 0, COMPLEX_NO);
// ... your code
}
static void mdlStart(SimStruct *S)
{
// ... your code
// Access bus/struct information
int32_T* __dtBusInfo = (int32_T*)ssGetDWork(S, 0);
// Get common data type Id
DTypeId __YOURBUSId = ssGetDataTypeId(S, "YOURBUS");
DTypeId __int32Id = ssGetDataTypeId(S, "int32");
DTypeId __doubleId = ssGetDataTypeId(S, "double");
// Get information for accessing YOURBUS.ui32_header_val
__dtBusInfo[0] = ssGetBusElementOffset(S, __YOURBUSId, 0);
__dtBusInfo[1] = ssGetDataTypeSize(S, __int32Id);
// Get information for accessing YOURBUS.f64_header_val
__dtBusInfo[2] = ssGetBusElementOffset(S, __YOURBUSId, 1);
__dtBusInfo[3] = ssGetDataTypeSize(S, __doubleId);
// ... your code
static void mdlOutputs(SimStruct *S, int_T tid)
{
// ... your code
char *inputPort = (char*)(ssGetInputPortSignal(S, 0)); // Cast it to an 8Bit long Pointer here char
YOURSTRUCT yourCStruct;
memcpy(&yourCStruct.ui32_header_val, inputPort + __dtBusInfo[0], __dtBusInfo[1]);
memcpy(&yourCStruct.f64_header_val, inputPort + __dtBusInfo[2], __dtBusInfo[3]);
// ... your code
}