【问题标题】:P/Invoking const char pointer and int referenceP/Invoking const char 指针和 int 引用
【发布时间】:2019-01-24 10:53:46
【问题描述】:

我正在尝试在 C# 中 P/Invoke 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);

【问题讨论】:

  • 我认为您不能使用与 char* 等效的字符串,请参阅此帖子:stackoverflow.com/questions/2568436/dllimport-and-char。我看到的第二个问题是,您无法将 C 库中的 Rectangle 结构与 Managed System.Drawing.Rectangle 进行比较,因此您需要自己重新定义它。希望这会有所帮助...
  • @feal,我的错,这里是更新版本,正在使用重新定义的 Rectangle scruct。
  • 我写的字符串 char 怎么样?
  • @feal,我尝试了 [MarshalAs(UnmanagedType.LPStr)] 属性并按照帖子中的描述传递了原始 IntPtr,但仍然有该异常((

标签: c# c .net pinvoke dllimport


【解决方案1】:

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

有一些工具可以帮助生成这些签名。使用 P\Invoke 互操作助手:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-02
    • 2011-03-07
    • 2013-06-12
    相关资源
    最近更新 更多