C#:多个声明的一个属性(DLLImport)

时间:2013-04-03 07:44:51

标签: c# attributes dllimport

我正在使用[DLLImport]属性访问.NET代码中的一堆C ++函数。 现在,我通过以下方式完成所有功能:

const string DLL_Path = "path\\to\\my\\dll.dll";

[DllImport(DLL_Path, 
    CallingConvention = CallingConvention.StdCall, 
    CharSet = CharSet.Ansi)] 
public static extern int MyFunction1();

[DllImport(DLL_Path, 
    CallingConvention = CallingConvention.StdCall, 
    CharSet = CharSet.Ansi)]
public static extern ErrorCode MyFunction2(int id);

[DllImport(DLL_Path, 
    CallingConvention = CallingConvention.StdCall, 
    CharSet = CharSet.Ansi)]
public static extern ErrorCode MyFunction3(string server, byte timeout, 
    ref int connection_id, ref DeviceInfo pInfos);

[DllImport(DLL_Path, 
    CallingConvention = CallingConvention.StdCall,
    CharSet = CharSet.Ansi)]
public static extern ErrorCode MyFunction4([MarshalAs(UnmanagedType.LPArray)] byte[] pVersion, 
    ref int psize);

[DllImport(DLL_Path, 
    CallingConvention = CallingConvention.StdCall, 
    CharSet = CharSet.Ansi)]
public static extern ErrorCode MyFunction5(int errorcode, 
    [MarshalAs(UnmanagedType.LPTStr)] string pmsg, ref int psize);

这并不令人满意:属性的重复似乎效率低下并且破坏了函数原型的可读性。特别是因为我有20或30个函数要导入。

我想知道我是否只能在某个地方拥有[DllImport(DLL_Path, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]部分并更清楚地识别出函数定义,就像这个伪代码一样:

const string DLL_Path = "path\\to\\my\\dll.dll";
// some code defining a section which tells that the next functions are DLLImport
[DllImport(DLL_Path, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)] 
{
    public static extern int MyFunction1();

    public static extern ErrorCode MyFunction2(int id);

    public static extern ErrorCode MyFunction3(string server, byte timeout, ref int connection_id, ref DeviceInfo pInfos);

    public static extern ErrorCode MyFunction4([MarshalAs(UnmanagedType.LPArray)] byte[] pVersion, ref int psize);

    public static extern ErrorCode MyFunction5(int errorcode, [MarshalAs(UnmanagedType.LPTStr)] string pmsg, ref int psize);
}

这可能吗?
我在SO中发现了这个问题:Shorten amount of DllImport in C#?但它建议通过LoadLibraryGetProcAddress动态加载函数,我发现这些函数的可读性较低。

1 个答案:

答案 0 :(得分:6)

不,没有办法将属性简化为单个声明。您需要将属性应用于所有方法。

但您至少可以将属性声明缩短为[DllImport(DLL_Path)],因为您为CallingConventionCharSet指定的值与默认值相同。