我一直在使用 CBLOCK4 在 Scilab/Xcos 中开发自己的块。块内的 C 语言代码如下:
#include <stdio.h>
#include "scicos_block4.h"
#define U ((SCSREAL_COP *)GetRealInPortPtrs(block, 1))
#define Y ((SCSREAL_COP *)GetRealOutPortPtrs(block, 1))
#define X ((SCSREAL_COP *)GetState(block))
#define dX ((SCSREAL_COP *)GetDerState(block))
#define Xk ((SCSREAL_COP *)GetDstate(block))
#define W ((SCSREAL_COP *)GetWorkPtrs(block))
// parameters
#define N (GetIparPtrs(block)[0])
typedef struct
{
double *buffer;
double *sum;
int *index;
}MovingAverage_t;
FILE *f;
void MovingAverage(scicos_block *block,int flag)
{
MovingAverage_t *ptr;
int bufferPos;
if(flag == 4)
{
/* init */
f = fopen("Debug.txt", "w");
if((*(block->work) = (MovingAverage_t *)scicos_malloc(sizeof(MovingAverage_t))) == NULL)
{
set_block_error(-16);
return;
}
ptr = (MovingAverage_t*)*block->work;
fprintf(f, "ptr: %ld \n", ptr);
if((ptr->buffer = (double*)scicos_malloc(sizeof(double)*N)) == NULL)
{
scicos_free(*(block->work));
fclose(f);
set_block_error(-16);
return;
}
if((ptr->sum = (double*)scicos_malloc(sizeof(double))) == NULL)
{
scicos_free(*(ptr->buffer));
scicos_free(*(block->work));
fclose(f);
set_block_error(-16);
return;
}
if((ptr->index = (int*)scicos_malloc(sizeof(int))) == NULL)
{
scicos_free(*(ptr->buffer));
scicos_free(*(ptr->sum));
scicos_free(*(block->work));
fclose(f);
set_block_error(-16);
return;
}
fprintf(f, "ptr->buffer: %ld \n", ptr->buffer);
fprintf(f, "ptr->sum: %ld \n", ptr->sum);
fprintf(f, "ptr->index: %ld \n", ptr->index);
int i;
for(i = 0; i < N; i++)
{
ptr->buffer[i] = 0;
}
*(ptr->sum) = 0;
*(ptr->index) = 0;
for(i = 0; i < N; i++)
{
fprintf(f, "buffer[%d]: %f\n", i, ptr->buffer[i]);
}
fprintf(f, "*(ptr->sum): %f\n", *(ptr->sum));
fprintf(f, "*(ptr->index): %d\n", *(ptr->index));
}
else if(flag == 1)
{
fprintf(f, "In: %f \n", U[0]);
ptr->buffer[0] = U[0];
int i;
for(i = 0; i < N; i++)
{
fprintf(f, "buffer[%d]: %f\n", i, ptr->buffer[i]);
}
}
else if (flag == 5)
{
/* ending */
scicos_free(*(block->work));
fclose(f);
}
}
为了完整起见,我还附上了 sccos_block 结构:
typedef struct
{
int nevprt;
voidg funpt;
int type;
int scsptr;
int nz;
double *z;
int noz;
int *ozsz;
int *oztyp;
void **ozptr;
int nx;
double *x;
double *xd;
double *res;
int *xprop;
int nin;
int *insz;
void **inptr;
int nout;
int *outsz;
void **outptr;
int nevout;
double *evout;
int nrpar;
double *rpar;
int nipar;
int *ipar;
int nopar;
int *oparsz;
int *opartyp;
void **oparptr;
int ng;
double *g;
int ztyp;
int *jroot;
char *label;
void **work;
int nmode;
int *mode;
char *uid;
}scicos_block;
我能够成功编译代码,但如果我运行包含我的 CBLOCK4 块的模拟,我总是会收到以下错误消息:
警告 !!!Scilab 在“scicosim”函数中发现了一个严重错误 (EXCEPTION_ACCESS_VIOLATION)。保存数据并重新启动 Scilab。
并且模拟也没有开始。我发现如果我删除 CBLOCK4 块中的以下代码行,模拟就会开始工作:
ptr->buffer[0] = U[0];
int i;
for(i = 0; i < N; i++)
{
fprintf(f, "buffer[%d]: %f\n", i, ptr->buffer[i]);
}
我怀疑我的 C 代码中有一些错误(可能与内存分配有关),但我找不到它。有人有使用 Scilab/Xcos CBLOCK4 的经验吗?