我正在使用[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的量?但它建议通过LoadLibrary
和GetProcAddress
动态加载函数,我认为这种方法不太易读。