You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#调用MATLAB Coder生成的DLL返回字符串时触发System.AccessViolationException

问题:C#调用MATLAB Coder导出的DLL字符串返回值时触发内存访问异常

相关代码与生成文件

MATLAB原代码

function fileID = simpleRead() %#codegen
    fileID = "test";
end

MATLAB Coder生成的C文件(simpleRead.c)

#include "simpleRead.h"
#include "simpleRead_types.h"

void simpleRead(rtString *fileID)
{
  fileID->Value[0] = 't';
  fileID->Value[1] = 'e';
  fileID->Value[2] = 's';
  fileID->Value[3] = 't';
}

对应的头文件(simpleRead_types.h)

#ifndef SIMPLEREAD_TYPES_H
#define SIMPLEREAD_TYPES_H

/* Include Files */
#include "rtwtypes.h"

/* Type Definitions */
#ifndef typedef_rtString
#define typedef_rtString
typedef struct {
  char Value[4];
} rtString;
#endif /* typedef_rtString */

#endif

我的C#调用代码

using System;
using System.Runtime.InteropServices;
class Programm
{
    [DllImport("simpleRead.dll")]
    public static extern string simpleRead();

    static void Main()
    {
        simpleRead();
    }
}

触发的错误

System.AccessViolationException: "Attempted to read or write protected memory. This is often an indication that other memory is corrupt."

已尝试的无效方案

  • 改为返回double类型时可以正常运行,但返回字符串场景下失效
  • 将C#的函数定义改为public static extern void simpleRead(out string res);并通过out参数调用,无效
  • 直接将函数返回值存入字符串变量,无效

有人能推测问题出在哪里吗?

内容的提问来源于stack exchange,提问作者user23348185

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 16:00:06