代码之家  ›  专栏  ›  技术社区  ›  Will Eddins ianpoley

当涉及指针时,如何P/Invoke

  •  7
  • Will Eddins ianpoley  · 技术社区  · 16 年前

    public int USB4_Initialize(short* device);
    public int USB4_GetCount(short device, short encoder, unsigned long* value);
    

    // Pointer as an input
    short device = 0; // Always using device 0.
    USB4_Initialize(&device);
    
    // Pointer as an output
    unsigned long count;
    USB4_GetCount(0,0,&count); // count is output
    

    我在C#中的第一次尝试导致以下P/调用:

    [DllImport("USB4.dll")]
    public static extern int USB4_Initialize(IntPtr deviceCount); //short*
    
    [DllImport("USB4.dll")]
    public static extern int USB4_GetCount(short deviceNumber, short encoder, IntPtr value); //ulong*
    

    如何在C++中使用这些函数,与上面的C++代码相同? 有没有更好的方法来声明这些类型,或者使用 MarshalAs

    2 回复  |  直到 16 年前
        1
  •  15
  •   JaredPar    16 年前

    如果指针指向单个基元类型而不是数组,请使用ref/out来描述参数

    [DllImport("USB4.dll")]
    public static extern int USB4_Initialize(ref short deviceCount);
    
    [DllImport("USB4.dll")]
    public static extern int USB4_GetCount(short deviceNumber, short encoder, ref uint32 value)
    

    在这些例子中,out可能更合适,但两者都可以。

        2
  •  1
  •   Adam Robinson    16 年前

    ref 这样的指针的关键字。

    [DllImport("USB4.dll")]
    public static extern int USB4_Initialize(ref short deviceCount); //short*
    
    [DllImport("USB4.dll")]
    public static extern int USB4_GetCount(short deviceNumber, short encoder, ref short value); //ulong*
    

    然后你可以这样称呼他们:

    short count = 0;
    
    USB4_Initialize(ref count);
    
    // use the count variable now.