使用p / invoke从C api调用函数

时间:2009-10-01 08:01:42

标签: c# pinvoke

我有一个C api,我正在使用p / invoke从我的C#应用​​程序中的api调用一个函数。功能签名是:

int APIENTRY GetData (CASHTYPEPOINTER cashData);

类型定义:

typedef CASHTYPE* CASHTYPEPOINTER;

typedef struct CASH
{
 int CashNumber;
 CURRENCYTYPE Types[24];
} CASHTYPE;   

typedef struct CURRENCY
{
 char Name[2];
 char NoteType[6];
 int NoteNumber;
} CURRENCYTYPE;

我的C#方法签名和数据类型如何?

谢谢。

2 个答案:

答案 0 :(得分:3)

您需要使用SizeConst指定数组大小:

using System;
using System.Runtime.InteropServices;

public static class MyCApi
{
    [StructLayout(LayoutKind.Sequential)]
    public struct CASHTYPE
    {
        public int CashNumber;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 24)]
        public CURRENCYTYPE[] Types;
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    public struct CURRENCYTYPE
    {
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 2)]
        public string Name;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 6)]
        public string NoteType;
        public int NoteNumber;
    }

    [DllImport("MyCApi.dll")]
    public static extern int GetData(ref CASHTYPE cashData);
}

答案 1 :(得分:0)

我认为它可能看起来像这样

      using System.Runtime.InteropServices;

        [StructLayout(LayoutKind.Sequential)]
        public struct CASH{
            public int CashNumber; 
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 24)]
            public CURRENCY Types[24];
        }   

    [ StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
        public struct CURRENCY {
             [MarshalAs( UnmanagedType.ByValTStr, SizeConst=2 )]
             public string Name;
             [MarshalAs( UnmanagedType.ByValTStr, SizeConst=6 )]
             public string NoteType;
             public int NoteNumber;
        }   

        class Wrapper {
            [DllImport("my.dll")]
            public static extern int GetData(ref CASH cashData}
        }