Interoperability Overview (C# Programming Guide)
Tools and techniques for interoperating between C# managed code and unmanaged code include Platform Invoke services and .NET Framework and COM interoperability tools.
Platform invoke
Platform invoke locates and calls unmanaged code as an exported function.It also marshals the call's arguments, such as input and output parameters, integers, strings, arrays, and structures, as needed. For more information, see Marshaling Data with Platform Invoke and Consuming Unmanaged DLL Functions.
Note
The Common Language Runtime (CLR) manages access to system resources. Calling unmanaged code outside of the CLR bypasses this security mechanism, and therefore presents a security risk. For example, unmanaged code might call resources in unmanaged code directly, bypassing CLR security mechanism. For more information, see .NET Framework Security.
Tools for Interoperability between the.NET Framework and COM
For calling COM APIs from managed code, use Type Library Importer (Tlbimp.exe) which takes a type library as input and outputs a .NET Framework assembly and associated managed metadata. You can then add this generated, .NET Framework assembly to your Visual Studio project as a Project Reference. For example, use
TlbImp comlibrary.dll /out: comlnetibrary.dll
and add a reference tocomlnetibrary.dll
in your project For more information, see Importing a Type Library as an Assembly and Calling COM Components from .NET Clients.For calling managed code from COM, use Type Library Exporter (Tlbexp.exe), which takes a managed assembly as input, and generates a type library containing COM definitions of all the public types defined in that assembly.
For calling managed components from COM clients, use Assembly Registration Tool (Regasm.exe), which reads the metadata within a .NET Framework assembly, and adds the registry entries so that COM clients can create managed classes.
For calling ActiveX controls, use Windows Forms ActiveX Control Importer (Aximp.exe), which takes an ActiveX control’s type library as input and generates a wrapper control that allows the control to be hosted in Windows Forms. For example,
Aximp activex.ocx
creates two files,viz.activex.dl
andAxactivex.dll
, and you can use as a project reference the auto-generatedAxactivex.dll
.
Note
To use the tools above such as registering a managed assembly for COMinterop, you must have administrator or a power user security permissions. For more information, see .NET Framework Security.
Interoperability Examples and Techniques
For more information, see Interop Marshaling Overview. For more information on techniques for interoperability, please see:
See Also
Concepts
C# Programming Guide
Custom Marshaling Overview
Other Resources
Marshaling Data with COM Interop
Interoperability in the .NET Compact Framework
Interop Marshaling