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

Gui*_*i13 7 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);
Run Code Online (Sandbox Code Playgroud)

这真是让人不悦:重复属性似乎效率低下,并且破坏了函数原型的可读性。特别是因为我要导入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);
}
Run Code Online (Sandbox Code Playgroud)

这可能吗?
我在SO中发现了这个问题:缩短C#中的DllImport数量?但是它建议通过LoadLibrary和动态加载函数GetProcAddress,但我觉得可读性较差。

Bot*_*000 7

不,无法将Attributes简化为单个声明。您需要将Attribute应用于所有方法。

但你至少可以缩短您的属性声明来[DllImport(DLL_Path)],因为你指定的价值观CallingConventionCharSet是一样的默认值。