我正在创建一个.net WebAPI,以促进从Delphi代码到C#的逐步迁移,但我们的代码库非常大,超过150万行代码.因此,我们试图将应用程序分解为小库,我们可以加载到C#API中,然后随着时间的推移逐渐重写函数或服务.我们决定我们的库将导出3个常见函数:
Initialize
Execute
DisposeStr
我们创建的所有dll都将导出这些函数,这样我们就有了一种通用的方式来与本机代码进行通信.
我的问题是,我将拥有DelphiEmployeeService.cs
、DelphiWorktimeService.cs
等(可能超过DelphiEmployeeService.cs
倍),并且我需要在每个服务包装器的开头有基本相同的行:
[LibraryImport("<DLLNAME>", EntryPoint = "Initialize")]
[return: MarshalAs(UnmanagedType.Bool)]
[UnmanagedCallConv(CallConvs = new Type[] { typeof(System.Runtime.CompilerServices.CallConvStdcall) })]
private static partial bool Initialize();
[LibraryImport("<DLLNAME>", EntryPoint = "Execute", StringMarshalling = StringMarshalling.Utf16)]
[UnmanagedCallConv(CallConvs = new Type[] { typeof(System.Runtime.CompilerServices.CallConvStdcall) })]
private static partial IntPtr Execute(string parameters);
[LibraryImport("<DLLNAME>", EntryPoint = "DisposeStr")]
[UnmanagedCallConv(CallConvs = new Type[] { typeof(System.Runtime.CompilerServices.CallConvStdcall) })]
private static partial void DisposeStr(IntPtr str);
为了解决这个问题,我想创建一个DelphiImplementation.cs
的基类,但我不确定如何让后代注册要加载的DLL名称.
我想要的是类似于
public class DelphiImplementation
{
protected abstract string LibraryName;
[LibraryImport(LibraryName, EntryPoint = "Initialize")]
[return: MarshalAs(UnmanagedType.Bool)]
[UnmanagedCallConv(CallConvs = new Type[] {typeof(System.Runtime.CompilerServices.CallConvStdcall) })]
private static partial bool Initialize();
[LibraryImport(LibraryName, EntryPoint = "Execute", StringMarshalling = StringMarshalling.Utf16)]
[UnmanagedCallConv(CallConvs = new Type[] { typeof(System.Runtime.CompilerServices.CallConvStdcall) })]
private static partial IntPtr Execute(string parameters);
[LibraryImport(LibraryName, EntryPoint = "DisposeStr")]
[UnmanagedCallConv(CallConvs = new Type[] { typeof(System.Runtime.CompilerServices.CallConvStdcall) })]
private static partial void DisposeStr(IntPtr str);
}
public class EmployeeDelphiService : DelphiImplementation
{
protected override string LibraryName => "Employee.dll"
}
这种事有可能吗