P /调用const char指针和int引用

时间:2019-01-24 10:53:47

标签: c# c .net pinvoke dllimport

我试图在C#中P /调用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 :(得分:1)

在使用P / Invoke传递指针时,例如使用activescrollIndex变量传递指针时,需要在托管签名中使用ref关键字。有关ref[out]之间的区别,请参见here

有一些工具可以帮助产生这些签名。使用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) ;