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

11

我正在使用[DLLImport]属性访问一堆C++函数,这些函数在我的.NET代码中。目前,我已经按照以下方式拥有所有的函数:

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

这是否可能?
我在stackoverflow上找到了这个问题:如何缩短C#中DllImport的量?但它建议通过LoadLibraryGetProcAddress动态加载函数,我认为这种方法不太易读。


答案是否定的,坚持你已经拥有的,无论它是否令人愉悦。 - Phil
这太刻薄了!有时候你不想改变事物的顺序吗? 或者你坚持自己所拥有的,从来不梦想一个更容易、更美观地导入DLL函数的世界? - Gui13
1个回答

7

不,没有办法将Attributes缩小到一个声明。您需要将Attribute应用于所有方法。

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


这对我来说已经足够好了,我会把它们放在声明的前面,这样更容易阅读。不过我还缺少一个“属性范围”...如果有的话,那将是一个很好的补充! - Gui13

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接