dSPACE.Runtime.InteropServices 0.23.1

Prefix Reserved
There is a newer version of this package available.
See the version list below for details.
dotnet add package dSPACE.Runtime.InteropServices --version 0.23.1                
NuGet\Install-Package dSPACE.Runtime.InteropServices -Version 0.23.1                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="dSPACE.Runtime.InteropServices" Version="0.23.1" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add dSPACE.Runtime.InteropServices --version 0.23.1                
#r "nuget: dSPACE.Runtime.InteropServices, 0.23.1"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install dSPACE.Runtime.InteropServices as a Cake Addin
#addin nuget:?package=dSPACE.Runtime.InteropServices&version=0.23.1

// Install dSPACE.Runtime.InteropServices as a Cake Tool
#tool nuget:?package=dSPACE.Runtime.InteropServices&version=0.23.1                

dSPACE COM tools

Nuget:Cli
Nuget:Lib
Nuget:LibBuildTask

Release License dSPACE

Unit Tests Example Tests Code Style Check

The command line client dscom is a replacement for tlbexp.exe and creates and registers TLBs from .NET assemblies.
The dSPACE.Runtime.InteropServices library contains various classes and methods for COM.
It can be used in net5+ or in net48 projects. With the library you can register assemblies and classes for COM and programmatically generate TLBs at runtime.
The dSPACE.Runtime.InteropServices.BuildTasks library provides build tasks which can be used to automatically generate TLBs at compile time.

This is an unstable prerelease. Anything may change at any time!

Introducing

Fortunately, .NET still supports COM, but there is no support for generating TLBs.
From the Microsoft documentation:

Unlike in .NET Framework, there is no support in .NET Core or .NET 5+ for generating a COM Type Library (TLB) from a .NET assembly.

https://docs.microsoft.com/en-us/dotnet/core/native-interop/expose-components-to-com

One main goal is to make dscom behave like tlbexp.exe.

Also, some classes are missing in .NET 5+ that were available in the full framework. This is where dSPACE.Runtime.InteropServices may be able to help.

Command Line Client

The command-line interface (CLI) tool dscom is a replacement for tlbexp.exe and OleView (View TypeLib).

It supports the following features:

  • Convert an assembly to a type library
  • Convert a type library to YAML file
  • Register a type library
  • Unregister a type library

Installation

The installation is quite simple. You can use dotnet tool to install the dscom binary if you want to create a 64Bit TLB.

dotnet tool install --global dscom

Here you can find all available versions:
https://www.nuget.org/packages/dscom/

Alternatively you can download dscom.exe from the relase page.
https://github.com/dspace-group/dscom/releases

Usage

Use dscom --help to get further information.

c:\> dscom --help
Description:
  dSPACE COM tools

Usage:
  dscom [command] [options]

Options:
  --version       Show version information
  -?, -h, --help  Show help and usage information

Commands:
  tlbexport <Assembly>         Export the assembly to the specified type library
  tlbdump <TypeLibrary>        Dump a type library
  tlbregister <TypeLibrary>    Register a type library
  tlbunregister <TypeLibrary>  Unregister a type library

Library

Usage:

dotnet add package dSPACE.Runtime.InteropServices

dSPACE.Runtime.InteropServices supports the following methods and classes:

  • TypeLibConverter
    • ConvertAssemblyToTypeLib
  • RegistrationServices
    • RegisterTypeForComClients
    • UnregisterTypeForComClients
    • RegisterAssembly
    • UnregisterAssembly

TypeLibConverter.ConvertAssemblyToTypeLib

If you miss the TypeLibConverter class and the ConvertAssemblyToTypeLib method in .NET, then the dSPACE.Runtime.InteropServices might help you. This method should behave compatible to the .NET Framework method.

public object? ConvertAssemblyToTypeLib(
  Assembly assembly,
  string tlbFilePath,
  ITypeLibExporterNotifySink? notifySink)

https://www.nuget.org/packages/dSPACE.Runtime.InteropServices/

Example:

using dSPACE.Runtime.InteropServices;

// The assembly to convert
var assembly = typeof(Program).Assembly;

// Convert to assembly
var typeLibConverter = new TypeLibConverter();
var callback = new TypeLibConverterCallback();
var result = typeLibConverter.ConvertAssemblyToTypeLib(assembly, "MyTypeLib.tlb", callback);

// Get the name of the type library
var typeLib2 = result as System.Runtime.InteropServices.ComTypes.ITypeLib2;
if (typeLib2 != null)
{
    typeLib2.GetDocumentation(-1, out string name, out _, out _, out _);
    Console.WriteLine($"TypeLib name: {name}");
}

// The callback to load additional type libraries, if necessary
public class TypeLibConverterCallback : ITypeLibExporterNotifySink
{
    public void ReportEvent(ExporterEventKind eventKind, int eventCode, string eventMsg)
    {
        Console.WriteLine($"{eventCode}: {eventMsg}");
    }

    public object? ResolveRef(System.Reflection.Assembly assembly)
    {
        // Returns additional type libraries
        return null;
    }
}

RegistrationServices.RegisterTypeForComClients

The dSPACE.Runtime.InteropServices.RegistrationServices provides a set of services for registering and unregistering managed assemblies for use from COM.

This method is equivalent to calling CoRegisterClassObject in COM.
You can register a .NET class so that other applications can connect to it (For example as INPROC_SERVER or as a LOCAL_SERVER).

A outproc demo application is available here: examples\outproc

Example:

using dSPACE.Runtime.InteropServices;

var registration = new RegistrationServices();
var cookie = registration.RegisterTypeForComClients(typeof(Server.Common.Greeter), 
  RegistrationClassContext.LocalServer, 
  RegistrationConnectionType.MultipleUse);

Console.WriteLine($"Press enter to stop the server");
Console.ReadLine();

registration.UnregisterTypeForComClients(cookie);

RegistrationServices.RegisterAssembly

Registers the classes in a managed assembly to enable creation from COM.

using dSPACE.Runtime.InteropServices;

var registration = new RegistrationServices();

// Register MyAssembly
registration.RegisterAssembly(typeof(MyAssembly), true);

// Unregister MyAssembly
registration.UnregisterAssembly(typeof(MyAssembly), true);

Build Tasks

The dSPACE.Runtime.InteropServices.BuildTasks assembly and NuGet package provide the ability to create type libraries for a certain assembly at compile time.

Build task usage

To create a type library at compile time, simply add a reference to the nuget package, e.g. by using the command line.

dotnet add package dSPACE.Runtime.InteropServices.BuildTasks

The result should be a line as follows in your .csproj file:

    <PackageReference Include="dSPACE.Runtime.InteropServices.BuildTasks" Version="0.17.0" NoWarn="NU1701">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>

Note: The extra attribute NoWarn="NU1701" is only required, if neither .NET 4.8 nor .NET 6.0 are targeted, since dotnet pack will currently not create a .NETStandard 2.0 compliant NuGet Package.

Using the native build task

The native build task is automatically selected, if a .NET 4.8 or .NET 6.0 assembly for Windows is being build using an x64 platform.

Using the CLI based task

The CLI task is automatically selected, if a .NET Standard 2.0 assembly is build. It is also chosen, if the target platform is set to x86.

Enforcing the usage of the CLI

It might be necessary to select the CLI based task. To do so, add the following property to your .csproj file:

<_DsComForceToolUsage>true</_DsComForceToolUsage>

This will enforce the usage of the DsCom as a command-line tool. Please note, that verbose logging will no longer be working.

Enforcing to stop the build, if an error occurs

The build tasks puts a warning to the build log, if the desired type library has not been created, even if the backend has reported a success.

This warning is issued with the warning code DSCOM001, which can be collected in the WarningsAsErrors array:

<WarningsAsErrors>$(WarningsAsErrors);DSCOM001</WarningsAsErrors>

This way the build stops, if the type library is not exported.

Parameters

The build task can be parameterized with the following properties:

Name Description
_DsComTlbExt Extension of the resulting type library. <br /> Default Value: .tlb
_DsComForceToolUsage Use DsCom Exe files to create the TLB <br/> Default value: false false
DsComTypeLibraryUniqueId Overwrite the library UUID <br/> Default Value: Empty Guid
DsComOverideLibraryName Overwrite the IDL name of the library. <br/> Default Value: Empty string
DsComRegisterTypeLibrariesAfterBuild Use regasm call after the build to register type library after the build <br/> Default value: false
DsComTlbExportAutoAddReferences Add referenced assemblies automatically to type libraries <br/> Default value: true
DsComTlbExportIncludeReferencesWithoutHintPath If a Reference assembly does not provide a HintPath Metadata, the item spec shall be task. <br/> Default value: false
_DsComExportTypeLibraryTargetFile Path to the resulting file. <br/> Default value: $(TargetDir)\$(TargetName)$(_DsComTlbExt) *
_DsComExportTypeLibraryAssemblyFile Path to the source assembly file. <br/> Default value: $(TargetPath) *

*) This value cannot be overridden.

The build task consumes the following items:

Name Description
DsComTlbExportTlbReferences Referenced type library files.
DsComTlbExportReferencePaths Directories containing type libraries to use for export.
DsComTlbExportAssemblyPaths Assemblies to add for the export.
DsComTlbAliasNames Names to use as aliases for types with aliases.

Example

<Project Sdk="Microsoft.NET.Sdk">
   <PropertyGroup>
      <DsComTypeLibraryUniqueId>f74a0889-2959-4e7b-9a1b-f41c54f31d74</DsComTypeLibraryUniqueId>
   </PropertyGroup>
   <ItemGroup>
    <DsComTlbExportTlbReferences Include="C:\Path\To\My.tlb" />
    <DsComTlbExportAssemblyPaths Include="C:\Path\To\Assemblies\Dependency.dll" />
    <DsComTlbExportReferencePaths Include="C:\Path\To\Additional\TypeLibraries\" />
   </ItemGroup>
</Project>

32Bit support

dscom installed by dotnet tool install can only handle AnyCPU or 64Bit assemblies and can only generate a 64bit TLB. Depending on whether you want to process 32bit or 64bit assemblies, you need to download different executables from the release page.

  • dscom.exe to create a 64Bit TLB from a AnyCPU or a 64Bit assembly
  • dscom32.exe to create a 32Bit TLB from a AnyCPU or a 32Bit assembly

Warning!
If your assembly is an AnyCPU assembly, then an yourassemblyname.comhost.dll is created as a 64 bit dll.
Therefore after calling regserv32.exe a 64 bit dll is registred.
To prevent this it is recommended that the assembly is compiled as a 32 bit assembly and not as an AnyCPU assembly.
see: https://github.com/dotnet/runtime/issues/32493

Migration notes (mscorelib vs System.Private.CoreLib)

Both assemblies are ComVisible=false but lot of .NET Framework types are ComVisible=true. But this is not the case for .NET (.NET Core and .NET >= 5).
Unlike mscorelib (the good old .NET Framework), no tlb is shipped for .NET.

As example the System.Exception class:

In case of mscorelib the System.Exception class is ComVisible=true:

[Serializable]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_Exception))]
[ComVisible(true)]
public class Exception : ISerializable, _Exception

In case of System.Private.CoreLib (.NET Core and .NET >=5), the Exception class is ComVisible=false

[Serializable]
[TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class Exception : ISerializable
{

The _Exception class interface (default interface in this case) is not available in .NET (.NET Core and .NET >=5).

Why can I load a .NET Framework library into a .NET application?

The magic is in TypeForwardedFromAttribute.
If you try to load an .NET Framework assembly inside a .NET (.NET Core and .NET >=5) application, the runtime will forward the original type to a type defined in the System.Private.CoreLib assembly.

classextern forwarder System.Exception
{
    .assemblyextern System.Private.CoreLib
}

Therefore you should make sure that you do not use any types from the mscorelib typelib in your .NET Framework project if you plan to migrate to .NET 5+

Limitations

RegisterAssembly

  • InProc Registration only will take place, if a comhost assembly is present.
  • No CustomRegisterFunction Or CustomUnRegisterFunction Attribute support
  • No PrimaryInteropAssembly Support
Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Framework net48 is compatible.  net481 was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • .NETFramework 4.8

    • No dependencies.
  • net6.0

    • No dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories (1)

Showing the top 1 popular GitHub repositories that depend on dSPACE.Runtime.InteropServices:

Repository Stars
dahall/Vanara
A set of .NET libraries for Windows implementing PInvoke calls to many native Windows APIs with supporting wrappers.
Version Downloads Last updated
1.12.2 76 11/24/2024
1.12.1 71 11/22/2024
1.12.0 74 11/20/2024
1.11.1 98 10/29/2024
1.11.0 93 10/3/2024
1.10.1 165 7/1/2024
1.10.0 521 4/30/2024
1.9.0 106 4/19/2024
1.8.0 151 4/15/2024
1.7.4 504 3/4/2024
1.7.3 202 1/9/2024
1.7.2 133 1/8/2024
1.7.1 190 12/12/2023
1.7.0 153 12/1/2023
1.6.0 265 11/20/2023
1.5.0 113 11/16/2023
1.4.0 122 11/15/2023
1.3.0 176 10/16/2023
1.2.0 317 9/18/2023
1.1.3 257 8/31/2023
1.1.2 177 8/10/2023
1.1.1 347 7/16/2023
1.1.0 172 6/20/2023
0.23.5 180 6/12/2023
0.23.4 182 5/8/2023
0.23.3 264 3/22/2023
0.23.1 296 3/17/2023
0.23.0 252 3/10/2023
0.22.1 282 2/24/2023
0.22.0 326 2/20/2023
0.21.0 342 2/16/2023
0.20.0 396 2/7/2023
0.19.1 416 1/19/2023
0.19.0 369 1/18/2023
0.18.3 406 1/5/2023
0.18.2 400 12/19/2022
0.18.1 410 12/19/2022
0.18.0 459 12/15/2022
0.17.0 433 11/29/2022
0.16.3 328 11/9/2022
0.16.2 337 11/3/2022
0.16.1 409 10/24/2022
0.16.0 444 9/20/2022
0.15.1 433 9/6/2022
0.15.0 456 7/29/2022
0.14.0 391 7/28/2022
0.13.0 449 7/18/2022
0.12.0 438 7/18/2022
0.11.0 462 7/18/2022
0.10.0 462 5/11/2022
0.9.0 465 4/5/2022
0.8.1 456 3/15/2022
0.8.0 470 3/15/2022
0.7.2 445 3/13/2022
0.7.1 450 3/13/2022
0.7.0 437 3/11/2022
0.6.0 458 3/10/2022
0.5.0 454 3/8/2022
0.4.0 460 3/7/2022
0.3.1 445 3/6/2022
0.3.0 424 3/4/2022
0.2.0 450 3/4/2022
0.1.0 491 3/3/2022