0

I try to use a DLL function (exported with the MATLAB Coder) in my C# code.

MATLAB Coder first produces a C file:

#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 looks like this:

#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

The C# code looks like this:

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

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

When I run the code, it gives me the error

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

By the way, the m-Code is

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

I already tried

  • returning a double instead of a string (worked)

  • defining the function as public static extern void simpleRead(out string res); and calling it with the out-parameter defined (didn't work)

  • saving the return value of the function directly into a string variable

Has anyone got a guess what the problem is?

Thanks in advance!
Philipp

1
  • You can't expect .NET to know what rtString is. Does this answer your question? calling c function from C# Commented Feb 5, 2024 at 8:59

1 Answer 1

0

It worked this way:

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);
    }
}

Thank you!

Sign up to request clarification or add additional context in comments.

1 Comment

Can you explain how to do that? Defining the return value as a StringBuilder object didn't work.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.