【发布时间】:2019-05-21 06:51:27
【问题描述】:
我有以下代码:
addstruct.h:
#ifndef ADDSTRUCT_H
#define ADDSTRUCT_H
typedef struct {
double* x;
double* y;
} StructC;
void addstruct(double *a, double *b, const StructC *structc, int len);
#endif
addstruct.c:
#include "addstruct.h"
void addstruct(double *a, double *b, StructC *structc, int len)
{
for (int i=0; i<len; i++)
{
structc->x[i]=a[i]+b[i];
structc->y[i]=-1*(a[i]+b[i]);
}
}
calladdstruct.m:
function S = calladdstruct(A,B) %#codegen
if coder.target('MATLAB')
else
coder.updateBuildInfo('addSourceFiles','addstruct.c');
L=1000;
Sx=zeros(1,L); Sy=zeros(1,L);
StructC=struct('x',{Sx}, 'y',{Sy});
coder.cstructname(StructC, 'StructC', 'extern', 'HeaderFile', 'addstruct.h');
coder.ceval('addstruct', coder.rref(A), coder.rref(B), coder.ref(StructC), int32(numel(Sx)));
S=sum(StructC.x);
sprintf('sumx: %s', char( num2ascii(S,0) ))
S=sum(StructC.y);
sprintf('sumy: %s', char( num2ascii(S,0) ))
end
end
和 main.c 在 Visual Studio 中:
#include "calladdstruct.h"
#include "calladdstruct_initialize.h"
#include "calladdstruct_terminate.h"
#include <stdio.h>
int main()
{
double S;
double xarr[3]={1,2,3};
double yarr[3]={1,2,3};
calladdstruct_initialize();
S = calladdstruct(xarr, yarr);
printf("%f\n", S);
calladdstruct_terminate();
getchar();
return 0;
}
当我在 Visual Studio 中运行它时,我得到了错误
Exception Thrown at (calladdstruct.dll) in calladdstruct.exe: Access violation writing location
这是为什么?
【问题讨论】:
-
只是一个猜测,但是您的 addstruct 将访问 xarr 和 yarr 超出范围的方式,因为它们是 3 长,但是您的代码将尝试访问 1000 个位置,这些位置甚至可能超出您的程序内存范围。错误消息似乎表明写访问冲突,但我看不出它可能在哪里。
-
警告,
addstruct声明和定义的原型不同(一个有const,另一个没有)。 (你的编译器应该警告你) -
即使我在
calladdstruct.m中将L更改为L=3,我仍然会遇到同样的错误 -
我还更改了
addstruct,因此声明和定义都没有const。没有摆脱错误