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

标签 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);

这是相当不顺眼的:属性的重复似乎效率低下并且破坏了函数原型(prototype)的可读性。特别是因为我有大约 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 动态加载函数,我觉得这不太可读。

最佳答案

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

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

关于C#:一个属性用于多个声明 (DLLImport),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15781627/

相关文章:

c# - WPF 自定义形状

c# - 将字符串拆分为二维数组

c# - 只接受实现特定接口(interface)的类的方法

html - 添加自定义属性

JQuery 工具 - 使用文本/链接调用叠加 - 使用 rel 属性?

c# - 从 c# 调用的非托管 c++ dll,在 dll 中使用 CString 时崩溃

header-files - 如何在 CANoe/CAPL 中包含 .h 或 .dll 文件

c# - 来自 Request.Url.ToString() 的字符串在操作/比较第一个字符时神秘地更改为另一个字符串

java - 如何在 JSP (Struts2) 中访问动态属性

c# - 从 C# 调用非托管 C++