0

I'm trying to P/Invoke C function in C# but always getting System.AccessViolationException. Please help me understand what am I doing wrong?

C code:

RAYGUIDEF bool GuiListView(Rectangle bounds, const char *text, int *active, int *scrollIndex, bool editMode);

C# code:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct Rectangle
{
    public float x;
    public float y;
    public float width;
    public float height;

    public Rectangle(float x, float y, float width, float height)
    {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    } 
}

[DllImport(nativeLibName,CallingConvention = CallingConvention.Cdecl)]
            public static extern bool GuiListView(Rectangle bounds, [MarshalAs(UnmanagedType.LPStr)]string text,[Out] int active, [Out] int scrollIndex, bool editMode);
Antonybae
  • 3
  • 6
  • I think you cannot use a string equivalent to char* see this post: https://stackoverflow.com/questions/2568436/dllimport-and-char. The second problem i see, is that you cant compare the Rectangle struct from the C library with the Managed System.Drawing.Rectangle so you would need to redefine it yourself. Hope this helps... – Felix Almesberger Jan 24 '19 at 11:02
  • @feal, my bad, here is updated version, am using redifined Rectangle scruct. – Antonybae Jan 24 '19 at 11:14
  • what about the string char thing i wrote? – Felix Almesberger Jan 24 '19 at 11:17
  • @feal, i tried [MarshalAs(UnmanagedType.LPStr)] attribute and passing raw IntPtr as described in post, but still having that exception(( – Antonybae Jan 24 '19 at 11:47

1 Answers1

1

When passing a pointer with P/Invoke, such as with your active and scrollIndex variables, you need to use the ref keyword in the managed signature. See here for the difference between ref and [out].

There are tools available to assist with producing these signatures. Using P\Invoke Interop Assistant:

    [System.Runtime.InteropServices.DllImportAttribute("<Unknown>", EntryPoint="GuiListView")]
    [return: System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.I1)]
public static extern  bool GuiListView(Rectangle bounds, [System.Runtime.InteropServices.InAttribute()] [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPStr)] string text, ref int active, ref int scrollIndex, [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.I1)] bool editMode) ;
mnistic
  • 10,866
  • 2
  • 19
  • 33