P / Invoking const char указатель и ссылка int - PullRequest
0 голосов
/ 24 января 2019

Я пытаюсь вызвать функцию P / Invoke C в C #, но всегда получаю System.AccessViolationException.Пожалуйста, помогите мне понять, что я делаю не так?

C код:

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

C # код:

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

1 Ответ

0 голосов
/ 24 января 2019

При передаче указателя с помощью P / Invoke, например, с переменными active и scrollIndex, необходимо использовать ключевое слово ref в управляемой подписи.См. здесь для разницы между ref и [out].

Существуют инструменты, которые могут помочь в получении этих подписей.Использование 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) ;
...