【问题标题】:Exception thrown: Access violation writing location for Matlab Coder in Visual Studio抛出异常:Visual Studio 中 Matlab Coder 的访问冲突写入位置
【发布时间】: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。没有摆脱错误

标签: c matlab exception


【解决方案1】:

结构“StructC”的声明与 MATLAB Coder 的预期不符。尝试在 coder.cstructname 中生成不带“extern”参数的代码,以查看预期的类型。然后在你的手写定义中使用它。

如果您需要特定的结构格式,请使用 coder.opaque 和 coder.ceval 专门与之交互,这样您就不会假设内存布局必须在 MATLAB Coder 生成的数据和您的手写代码之间匹配。

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    • 2021-07-12
    • 2020-03-28
    • 2022-01-08
    • 1970-01-01
    • 2022-12-20
    • 2022-06-16
    相关资源
    最近更新 更多