9

我正在使用该[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#? 但它建议通过LoadLibraryand动态加载函数GetProcAddress,我发现它的可读性较差。

4

1 回答 1

7

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

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

于 2013-04-03T07:50:43.137 回答