从 C# 中的 DLL 函数返回字符串时出现 System.AccessViolationException

问题描述 投票:0回答:1

我尝试在我的 C# 代码中使用 DLL 函数(使用 MATLAB Coder 导出)。

MATLAB Coder 首先生成一个 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:“尝试读取或写入受保护的内存。这通常表明其他内存已损坏。”

顺便说一句,m-Code 是

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

我已经尝试过了

  • 返回双精度值而不是字符串(有效)

  • 将函数定义为 public static extern void simpleRead(out string res);并使用定义的输出参数调用它(不起作用)

  • 将函数的返回值直接保存到字符串变量中

有人猜出问题是什么吗?

提前致谢!
菲利普

c# string matlab dll
1个回答
0
投票

它是这样工作的:

using System.Runtime.InteropServices;

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct RtString
{
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 4)]
    public string Value;
}

class Programm
{
    [DllImport("simpleRead.dll")] 
    public static extern void simpleRead(out RtString res);

    static void Main()
    {
        RtString res;
        simpleRead(out res);
    }
}

谢谢!

© www.soinside.com 2019 - 2024. All rights reserved.