C# System.Runtime.InteropServices related learning summary

Solution of System.Runtime.InteropServices.COMException

http://www.jb51.net/article/17629.htm

perfectly solves "System.Runtime.InteropServices.COMException" occurs when using VS2008 to continue developing web projects on another computer, and then the project cannot be loaded." 

Only You need to open the project configuration file *.csproj, change <UseIIS>True</UseIIS> to False, then you can load the project normally, and then reconfigure it to normal IIS. 
========

Exception Details: System.Runtime.InteropServices.COMException

http://www.cnblogs.com/star250/archive/2008/03/06/1093720.htmlInvalid


category string
Description : During the execution of the current web request, an unhandled exception occurred. Check the stack trace for details about the error and where in the code it occurred. 


Exception Details: System.Runtime.InteropServices.COMException: Invalid Category String


Source  Error:


 Line 88: String ss=Server.MapPath("rpt\\S_CardTradeDayDetail.rpt").ToString();
            Line 89: CrystalReportSource1.ReportDocument .Load(Server.MapPath("rpt\\S_CardTradeDayDetail.rpt"), OpenReportMethod.OpenReportByTempCopy);
            
There is such a problem when a server is deployed

There are several ways to solve  the permission problem
. The first method is to assign access to the asp.net account Com permission, configure com+ 
type 2. Add 
<identity impersonate="true" userName="account name with administrator privilege" password="corresponding password"  in the system.web section of web.config
To simulate an identity with administrative privileges to run your code, 


I used the second method. Why is there no such problem on other servers? It may be that the server privileges are set too high. Please answer it if you know it. Thanks! 


2008-4-11 I found that the second method does not work, the third method: add user NETWORK SERVICE to the C:\WINDOWS\Temp folder, and have the modification permission. //I think this is because Crystal Reports needs to generate temporary files in C:\WINDOWS\Temp
========

System.Runtime.InteropServices Namespace

https://msdn.microsoft.com/zh-cn/library/system.runtime.interopservices(v=vs.80).aspx
.NET Framework 2.0 Other versions 
The System.Runtime.InteropServices namespace provides various support COM Member of interop and platform invocation services. If you're not familiar with these services, see Interoperating with Unmanaged Code.
This namespace provides several categories of functionality, as shown in the following table. Properties control marshaling behavior, such as how structures are arranged or strings are represented. The most important of these are DllImportAttribute (which can be used to define the platform call method used to access unmanaged APIs) and MarshalAsAttribute (which can be used to specify how to marshal data between managed and unmanaged memory). Classes Class
Description Public class AutomationProxyAttribute Specifies whether the type should be marshaled using the automation marshaler or a custom proxy and stub. Public class BestFitMappingAttribute Controls whether Unicode characters are converted to their closest matching ANSI characters. Public class BStrWrapper Marshals data of type VT_BSTR from managed to unmanaged code. This class cannot be inherited. D
 



ClassInterfaceAttribute specifies the type of class interface to generate (if any) for classes exposed to COM.
Public class CoClassAttribute Specifies the class identifier of a coclass imported from a type library.
Public class ComAliasNameAttribute Indicates the COM alias for a parameter or field type.
Public class ComCompatibleVersionAttribute Indicates to COM clients that all classes in the current version of an assembly are compatible with classes in earlier versions of the assembly.
Public class ComConversionLossAttribute Indicates that information about the import of a class or interface from a type library to an assembly was lost.
Public class ComDefaultInterfaceAttribute Specifies the default interface to expose to COM. This class cannot be inherited.
Public class ComEventInterfaceAttribute Identifies the source interface and the class that implements the methods of the event interface (generated when the coclass is imported from the COM type library).
Public class COMException The exception thrown when an unrecognized HRESULT is returned from a COM method call.
D ComImportAttribute indicates that the attributed type was previously defined in COM.
Public class ComRegisterFunctionAttribute Specifies the method called when an assembly is registered for use with COM; this can be used for execution of user-written code during the registration process.
Public class ComSourceInterfacesAttribute Identifies for an attributed class a set of interfaces exposed as COM event sources.
Public class ComUnregisterFunctionAttribute Specifies the method called when an assembly for COM is unregistered; this can be used for execution of user-written code during unregistering.
Public class ComVisibleAttribute Controls the COM accessibility of individual managed types, members, or all types in an assembly.
The public class CriticalHandle represents a wrapper class for handle resources.
Public class CurrencyWrapper Wraps an object that the marshaler should marshal as VT_CY.
Public class DefaultCharSetAttribute Specifies the value of the CharSet enumeration. This class cannot be inherited.
D DefaultParameterValueAttribute sets the default value for a parameter when called from a language that supports default parameters. This class cannot be inherited.
Public class DispatchWrapper Wraps an object that the marshaler should marshal as VT_DISPATCH.
Public class DispIdAttribute Specifies the COM dispatch identifier (DISPID) of a method, field, or property.
Public class DllImportAttribute Indicates that the attributed method is exposed by an unmanaged dynamic-link library (DLL) as a static entry point.
Public class ErrorWrapper Wraps an object that the marshaler should marshal as VT_ERROR.
Public class ExtensibleClassFactory enables customization of managed objects that extend from unmanaged objects during creation.
Public class ExternalException The exception base type for all COM Interop exceptions and Structured Exception Handling (SEH) exceptions.
Public class FieldOffsetAttribute Indicates the physical location of a field within the unmanaged representation of a class or structure.
Public class GuidAttribute Provide an explicit System.Guid when no automatic GUID is required.
Public class HandleCollector tracks unhandled handles and forces garbage collection when a specified threshold is reached.
Public class IDispatchImplAttribute Indicates which IDispatch implementation the common language runtime uses when exposing dual and dispatch interfaces to COM.
Public class ImportedFromTypeLibAttribute Indicates that a type defined within an assembly was originally defined in a type library.
Public class InAttribute Indicates that data should be marshaled from the caller to the callee, not returned to the caller.
Public class InterfaceTypeAttribute Indicates whether the managed interface is dual, dispatch-only, or IUnknown-only when exposed to COM.
Public class InvalidComObjectException Exception thrown when an invalid COM object is used.
Public class InvalidOleVariantTypeException Exception thrown by the marshaler when it encounters a parameter of type Variant that cannot be marshaled to managed code.
Public class LCIDConversionAttribute Indicates that the unmanaged signature of the method requires a locale identifier (LCID) parameter.
Public class Marshal provides a set of methods for allocating unmanaged memory, copying blocks of unmanaged memory, converting managed types to unmanaged types, and other miscellaneous methods used when interacting with unmanaged code.
Public class MarshalAsAttribute Indicates how to marshal data between managed and unmanaged code.
Public class MarshalDirectiveException Exception thrown when the marshaller encounters a MarshalAsAttribute that it does not support.
Public class OptionalAttribute indicates that a parameter is optional.
Public class OutAttribute Indicates that data should be marshaled back from the callee to the caller.
Public class PreserveSigAttribute Indicates that HRESULT or retval signature transitions that occur during a COM interop call should be canceled.
Public class PrimaryInteropAssemblyAttribute Indicates that this attributed assembly is the primary Interop assembly.
Public class ProgIdAttribute allows the user to specify the ProgID of a class.
Public class RegistrationServices Provides a set of services for registering and unregistering managed assemblies for use from COM.
Public class RuntimeEnvironment provides a collection of static methods that return information about the common language runtime environment.
Public class SafeArrayRankMismatchException Exception thrown when the rank of the incoming SAFEARRAY does not match the rank specified in the managed signature.
Public class SafeArrayTypeMismatchException Exception thrown when the type of the SAFEARRAY passed in does not match the type specified in the managed signature.
Public class SafeHandle Represents a wrapper class for operating system handles.
Public class SEHException Represents a Structured Exception Handler (SEH) error.
Public class SetWin32ContextInIDispatchAttribute This attribute has been deprecated.
Public class StandardOleMarshalObject replaces the standard common language runtime (CLR) free-threaded marshaler with the standard OLE STA marshaler.
D StructLayoutAttribute The StructLayoutAttribute class enables the user to control the physical layout of the data fields of a class or structure.
Public class TypeLibConverter Provides a set of services for converting managed assemblies to COM type libraries and vice versa.
Public class TypeLibFuncAttribute Contains the FUNCFLAGS originally imported for this method from the COM type library.
Public class TypeLibImportClassAttribute Specifies which Type has exclusive use of the interface. This class cannot be inherited.
Public class TypeLibTypeAttribute Contains the TYPEFLAGS originally imported for this type from the COM type library.
Public class TypeLibVarAttribute Contains the VARFLAGS originally imported from the COM type library for this field.
Public class TypeLibVersionAttribute Specifies the version number of an exported type library.
Public class UnknownWrapper Wraps an object that the marshaler should marshal as VT_UNKNOWN .
D UnmanagedFunctionPointerAttribute controls the marshaling behavior of delegate signatures passed in or out of unmanaged code as unmanaged function pointers. This class cannot be inherited.
Public class VariantWrapper marshals data of type VT_VARIANT | VT_BYREF from managed to unmanaged code. This class cannot be inherited.
Interfaces
  Interface Description
Public interface _Activator exposes the System.Activator class to unmanaged code.
Public interface _Assembly exposes the public members of the System.Reflection.Assembly class to unmanaged code.
Public interface _AssemblyBuilder exposes the System.Reflection.Emit.AssemblyBuilder class to unmanaged code.
Public interface _AssemblyName exposes the AssemblyName class to unmanaged code.
Public interface _Attribute exposes the System.Attribute class to unmanaged code.
public interface_ConstructorBuilder Exposes the System.Reflection.Emit.ConstructorBuilder class to unmanaged code.
Public interface _ConstructorInfo exposes the public members of the System.Reflection.ConstructorInfo class to unmanaged code.
Public interface _CustomAttributeBuilder exposes the System.Reflection.Emit.CustomAttributeBuilder class to unmanaged code.
Public interface _EnumBuilder exposes the System.Reflection.Emit.EnumBuilder class to unmanaged code.
Public interface _EventBuilder exposes the System.Reflection.Emit.EventBuilder class to unmanaged code.
Public interface _EventInfo exposes the public members of the System.Reflection.EventInfo class to unmanaged code.
Public interface _Exception exposes the public members of the System.Exception class to unmanaged code.
public interface_FieldBuilder Exposes the System.Reflection.Emit.FieldBuilder class to unmanaged code.
Public interface _FieldInfo exposes the public members of the System.Reflection.FieldInfo class to unmanaged code.
Public interface _ILGenerator exposes the System.Reflection.Emit.ILGenerator class to unmanaged code.
Public interface _LocalBuilder exposes the System.Reflection.Emit.LocalBuilder class to unmanaged code.
Public interface _MemberInfo exposes the public members of the System.Reflection.MemberInfo class to unmanaged code.
Public interface _MethodBase exposes the public members of the System.Reflection.MethodBase class to unmanaged code.
Public interface _MethodBuilder exposes the MethodBuilder class to unmanaged code.
Public interface _MethodInfo exposes the public members of the System.Reflection.MethodInfo class to unmanaged code.
public interface _MethodRental exposes the System.Reflection.Emit.MethodRental class to unmanaged code.
The public interface _Module exposes the Module class to unmanaged code.
Public interface _ModuleBuilder exposes the System.Reflection.Emit.ModuleBuilder class to unmanaged code.
Public interface _ParameterBuilder exposes the System.Reflection.Emit.ParameterBuilder class to unmanaged code.
Public interface _ParameterInfo exposes the System.Reflection.ParameterInfo class to unmanaged code.
Public interface _PropertyBuilder exposes the System.Reflection.Emit.PropertyBuilder class to unmanaged code.
Public interface _PropertyInfo exposes the public members of the System.Reflection.PropertyInfo class to unmanaged code.
public interface_SignatureHelper Exposes the System.Reflection.Emit.SignatureHelper class to unmanaged code.
The public interface _Thread exposes the System.Threading.Thread class to unmanaged code.
The public interface _Type exposes the public members of the System.Type class to unmanaged code.
Public interface _TypeBuilder exposes the System.Reflection.Emit.TypeBuilder class to unmanaged code.
The public interface ICustomAdapter provides a way for clients to access the actual object (rather than the adapter object distributed by the custom marshaler).
The public interface ICustomFactory enables users to write activation code for managed objects that extend MarshalByRefObject.
The public interface ICustomMarshaler is designed to provide custom wrappers for handling method calls.
Public interface IRegistrationServices Provides a set of services for registering and unregistering managed assemblies for use from COM.
Public interface ITypeLibConverter Provides a set of services for converting managed assemblies to COM type libraries and vice versa.
Public interface ITypeLibExporterNameProvider Provides name case control when exporting to a type library.
Public interface ITypeLibExporterNotifySink Provides a callback mechanism for the assembly converter to notify the caller of the status of the conversion, and to involve the caller in the conversion process itself.
The public interface ITypeLibImporterNotifySink provides a callback mechanism for the type library converter to notify the caller of the status of the conversion and to involve the caller in the conversion process itself.
The public interface UCOMIBindCtx should use BIND_OPTS instead.
The public interface UCOMIConnectionPoint should use IConnectionPoint instead.
The public interface UCOMIConnectionPointContainer should use IConnectionPointContainer instead.
The public interface UCOMIEnumConnectionPoints should use IEnumConnectionPoints instead.
Public interface UCOMIEnumConnections IEnumConnections should be used instead.
The public interface UCOMIEnumMoniker should use IEnumMoniker instead.
The public interface UCOMIEnumString should use IEnumString instead.
The public interface UCOMIEnumVARIANT should use IEnumVARIANT instead.
The public interface UCOMIMoniker should use IMoniker instead.
Public interface UCOMIPersistFile Note: This interface is now obsolete. IPersistFile should be used instead.
The public interface UCOMIRunningObjectTable should use IRunningObjectTable instead.
The public interface UCOMIStream should use IStream instead.
The public interface UCOMITypeComp should use ITypeComp instead.
The public interface UCOMITypeInfo should use ITypeInfo instead.
public interfaceUCOMITypeLib ITypeLib should be used instead.
Structures
  Structure Description
Public structure ArrayWithOffset encapsulates the array and offset within the specified array.
The public structure BIND_OPTS should use BIND_OPTS instead.
The public structure BINDPTR should use BINDPTR instead.
The public structure CONNECTDATA should use CONNECTDATA instead.
The public structure DISPPARAMS should use DISPPARAMS instead.
The public structure ELEMDESC should use ELEMDESC instead.
The public structure ELEMDESC.DESCUNION should use ELEMDESC.DESCUNION instead.
The public structure EXCEPINFO should be used instead EXCEPINFO.
Public structure FILETIME should use FILETIME instead.
public structure FUNCDESC FUNCDESC should be used instead.
Public structure GCHandle Provides methods for accessing managed objects from unmanaged memory.
Public structure HandleRef wraps a managed object that holds resource handles passed to unmanaged code using platform invoke.
The public structure IDLDESC should use IDLDESC instead.
The public structure PARAMDESC should use PARAMDESC instead.
The public structure STATSTG should use STATSTG instead.
The public structure TYPEATTR should use TYPEATTR instead.
The public structure TYPEDESC should use TYPEDESC instead.
The public structure TYPELIBATTR should use TYPELIBATTR instead.
The public structure VARDESC should use VARDESC instead.
public struct VARDESC.DESCUNION Note: This structure is obsolete. VARDESC.DESCUNION should be used instead.
Delegate
  Delegate Description
Public delegate ObjectCreationDelegate creates COM objects.
Enumeration
  Enumeration Description
Public enumeration AssemblyRegistrationFlags defines a set of flags that are used when registering an assembly.
Public enum CALLCONV should use CALLCONV instead.
Public enumeration CallingConvention Specifies the calling convention required to call methods implemented in unmanaged code.
Public enumeration CharSet Specifies what character set should be used for the marshaled string.
Public enumeration ClassInterfaceType Identifies the type of class interface generated for a class.
Public enumeration ComInterfaceType Identifies how to expose the interface to COM.
Public enumeration ComMemberType describes the type of COM member.
public enum DESCKIND DESCKIND should be used instead.
Public enumeration ExporterEventKind Describes the callbacks generated by a type library exporter when exporting a type library.
The public enum FUNCFLAGS should use FUNCFLAGS instead.
The public enum FUNCKIND should use FUNCKIND instead.
Public enumeration GCHandleType Indicates the types of handles that the GCHandle class can allocate.
Public enumeration IDispatchImplType Indicates which IDispatch implementation to use for a particular class.
The public enum IDLFLAG should use IDLFLAG instead.
public enum IMPLTYPEFLAGS should use IMPLTYPEFLAGS instead.
Public enumeration ImporterEventKind Describes the callbacks generated by a type library importer when importing a type library.
Public enum INVOKEKIND should use INVOKEKIND instead.
public enumeration LayoutKind Controls the layout of objects when exported to unmanaged code.
The public enum LIBFLAGS should use LIBFLAGS instead.
public enum PARAMFLAG should use PARAMFLAG instead.
Public enumeration RegistrationClassContext specifies the set of execution contexts in which class objects will be available to requests to construct instances.
Public enumeration RegistrationConnectionType defines the type of connection to class objects.
The public enum SYSKIND should use SYSKIND instead.
public enum TYPEFLAGS should use TYPEFLAGS instead.
Public enum TYPEKIND should use TYPEKIND instead.
Public enumeration TypeLibExporterFlags indicates how type libraries should be generated.
Public enumeration TypeLibFuncFlags Describes the native setting of FUNCFLAGS in the COM type library from which this method was imported.
public enum TypeLibImporterFlags Indicates how the assembly should be generated.
Public enumeration TypeLibTypeFlags Describes the native setting of TYPEFLAGS in the COM type library from which this type was imported.
Public enumeration TypeLibVarFlags Describes the original setting of VARFLAGS in the COM type library from which this variable was imported.
Public enumeration UnmanagedType Specifies how parameters or fields are marshaled to unmanaged code.
Public enumeration VarEnum Indicates how the elements of an array are marshaled when the array is marshaled from managed to unmanaged code as an UnmanagedType.SafeArray.
public enum VARFLAGS should use VARFLAGS instead.
========
GCHandle Structure
https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.gchandle(v=vs.110).aspx


.NET Framework (current version) Other Versions 
 
Provides a way to access a managed object from unmanaged memory.
Namespace:   System.Runtime.InteropServices
Assembly:  mscorlib (in mscorlib.dll)


Syntax
C#C++F#VB
[ComVisibleAttribute(true)]
public struct GCHandle
Properties
Name Description
System_CAPS_pubproperty IsAllocated
Gets a value indicating whether the handle is allocated.
System_CAPS_pubproperty Target
Gets or sets the object this handle represents.
Methods
Name Description
System_CAPS_pubmethod AddrOfPinnedObject()
Retrieves the address of an object in a GCHandleType.Pinned handle.
System_CAPS_pubmethodSystem_CAPS_static Alloc(Object)
Allocates a Normal handle for the specified object.
System_CAPS_pubmethodSystem_CAPS_static Alloc(Object, GCHandleType)
Allocates a handle of the specified type for the specified object.
System_CAPS_pubmethod Equals(Object)
Determines whether the specified GCHandle object is equal to the current GCHandle object.(Overrides ValueType.Equals(Object).)
System_CAPS_pubmethod Free()
Releases a GCHandle.
System_CAPS_pubmethodSystem_CAPS_static FromIntPtr(IntPtr)
Returns a new GCHandle object created from a handle to a managed object.
System_CAPS_pubmethod GetHashCode()
Returns an identifier for the current GCHandle object.(Overrides ValueType.GetHashCode().)
System_CAPS_pubmethod GetType()
Gets the Type of the current instance.(Inherited from Object.)
System_CAPS_pubmethodSystem_CAPS_static ToIntPtr(GCHandle)
Returns the internal integer representation of a GCHandle object.
System_CAPS_pubmethod ToString()
Returns the fully qualified type name of this instance.(Inherited from ValueType.)
Operators
Name Description
System_CAPS_puboperatorSystem_CAPS_static Equality(GCHandle, GCHandle)
Returns a value indicating whether two GCHandle objects are equal.
System_CAPS_puboperatorSystem_CAPS_static Explicit(GCHandle to IntPtr)
A GCHandle is stored using an internal integer representation.
System_CAPS_puboperatorSystem_CAPS_static Explicit(IntPtr to GCHandle)
A GCHandle is stored using an internal integer representation.
System_CAPS_puboperatorSystem_CAPS_static Inequality(GCHandle, GCHandle)
Returns a value indicating whether two GCHandle objects are not equal.
Remarks
The GCHandle structure is used with the GCHandleType enumeration to create a handle corresponding to any managed object. This handle can be one of four types: Weak, WeakTrackResurrection, Normal, or Pinned. When the handle has been allocated, you can use it to prevent the managed object from being collected by the garbage collector when an unmanaged client holds the only reference. Without such a handle, the object can be collected by the garbage collector before completing its work on behalf of the unmanaged client.
You can also use GCHandle to create a pinned object that returns a memory address to prevent the garbage collector from moving the object in memory.
When the handle goes out of scope you must explicitly release it by calling the Free method; otherwise, memory leaks may occur. When you free a pinned handle, the associated object will be unpinned and will become eligible for garbage collection, if there are no other references to it.
Examples
The following example shows an App class that creates a handle to a managed object using the GCHandle.Alloc method, which prevents the managed object from being collected. A call to the EnumWindows method passes a delegate and a managed object (both declared as managed types, but not shown), and casts the handle to an IntPtr. The unmanaged function passes the type back to the caller as a parameter of the callback function.
C#VB
using System;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Security.Permissions;


public delegate bool CallBack(int handle, IntPtr param);


public class LibWrap
{
// passing managed object as LPARAM
// BOOL EnumWindows(WNDENUMPROC lpEnumFunc, LPARAM lParam);


[DllImport("user32.dll")]
public static extern bool EnumWindows(CallBack cb, IntPtr param);
}


public class App
{
public static void Main()
{
Run();
}


        [SecurityPermission(SecurityAction.Demand, UnmanagedCode=true)]
public static void Run()
        {
TextWriter tw = System.Console.Out;
GCHandle gch = GCHandle.Alloc(tw);


CallBack cewp = new CallBack(CaptureEnumWindowsProc);


// platform invoke will prevent delegate to be garbage collected
// before call ends


LibWrap.EnumWindows(cewp, GCHandle.ToIntPtr(gch));
gch.Free();
        }


private static bool CaptureEnumWindowsProc(int handle, IntPtr param)
{
GCHandle gch = GCHandle.FromIntPtr(param);
TextWriter tw = (TextWriter)gch.Target;
tw.WriteLine(handle);
return true;
}
}
Version Information
Universal Windows Platform 
Available since 8
.NET Framework 
Available since 1.1
Portable Class Library 
Supported in: portable .NET platforms 
Silverlight 
Available since 2.0
Windows Phone Silverlight 
Available since 7.0
Windows Phone 
Available since 8.1
Thread Safety
Any public static ( Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
See Also
GCHandleType
System.Runtime.InteropServices Namespace
The Truth About GCHandles
========

GuidAttribute class

https://msdn.microsoft.com/zh-cn/library/system.runtime.interopservices.guidattribute.aspx
.NET Framework (current version) Other versions 
 
provide an explicit System.Guid which is not required when an automatic GUID appears.
Namespace: System.Runtime.InteropServices
Assembly: mscorlib (in mscorlib.dll)


Inheritance Hierarchy
System.Object
  System.Attribute
    System.Runtime.InteropServices.GuidAttribute


Syntax
C#C++F#VB
[AttributeUsageAttribute(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Delegate, 
Inherited = false)]
[ComVisibleAttribute(true)]
public sealed class GuidAttribute : Attribute
Constructor
Name Description
System_CAPS_pubmethod GuidAttribute(String) A new instance initializes the GuidAttribute class with the specified GUID. Property Name Description System_CAPS_pubproperty TypeId When implemented in a derived class, get the unique identifier of this Attribute. (Inherited from Attribute.) System_CAPS_pubproperty Value Gets the class of Guid. Method Name Description System_CAPS_pubmethod Equals(Object) This API supports the product infrastructure and should not be used directly from code. Returns a value indicating whether this instance is equal to the specified object. (Inherited from Attribute.) System_CAPS_pubmethod











GetHashCode() returns the hash code for this instance. (Inherited from Attribute.) System_CAPS_pubmethod GetType() Gets the Type of the current instance. (Inherited from Object.) System_CAPS_pubmethod IsDefaultAttribute() When overridden in a derived class, indicates whether this instance's value is the derived class' default value. (Inherited from Attribute.) System_CAPS_pubmethod Match(Object) When overridden in a derived class, returns a value indicating whether this instance is equal to the specified object. (Inherited from Attribute.) System_CAPS_pubmethod ToString () returns the string representing the current object. (Inherited from Object.) Explicit interface implementation Name Description System_CAPS_pubinterfaceSystem_CAPS_privmethod _Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) Maps a set of names to a corresponding set of scheduling identifiers. (Inherited from Attribute.)













System_CAPS_pubinterfaceSystem_CAPS_privmethod_Attribute.GetTypeInfo (UInt32, UInt32, IntPtr) Retrieves type information for an object, which can then be used to obtain type information for an interface. (Inherited from Attribute.) System_CAPS_pubinterfaceSystem_CAPS_privmethod_Attribute.GetTypeInfoCount (UInt32) Retrieves the number of type information interfaces provided by the object (0 or 1). (Inherited from Attribute.) System_CAPS_pubinterfaceSystem_CAPS_privmethod _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) Provides access to the properties and methods exposed by an object. (Inherited from Attribute.) Remarks You can apply this attribute to an assembly, interface, class, enumeration, structure, or delegate, although Tlbimp.exe (Type Library Importer) can apply it when you import a type library. The string passed to this property must be a format Guid that is an acceptable constructor parameter for this type. To avoid conflicts with the type Guid, use the long-named GuidAttribute explicitly. When a type must have a specific GUID, only an explicit GUID can be used. If this attribute is omitted, a GUID is automatically assigned. example









The following example demonstrates how to apply the GuidAttribute to a COM class exported to have a fixed GUID.
C#C++VB
using System;
using System.Runtime.InteropServices;


[GuidAttribute("9ED54F84-A89D-4fcd-A854-44251E925F09")]
public class SampleClass 
{
    // Insert class members here.
}
Version Information
Universal  Windows Platform
since Available since
.NET Framework 
1.1
Portable  Class Libraries
are supported in Portable .NET Platforms
Silverlight 
is available since 2.0
Windows Phone Silverlight 
is available since 7.0
Windows Phone 
is available since 8.1
Thread Safe
All public static (shared in Visual Basic) members of this type are thread-safe. All instance members are not guaranteed to be thread-safe.
See also
Guid
System.Runtime.InteropServices Namespace
Tlbimp.exe (Type Library Importer)
========

Use the DllImport method of the System.Runtime.InteropServices service to import unmanaged code assemblies  

http://blog.163.com/yuyi_84225505@126/blog/static/36297389201271602234279/
extern is mainly used to declare methods implemented externally. What is an external practical method? Generally speaking, it uses System.Runtime.InteropServices services The DllImport method imports an unmanaged code assembly. For example, calling system APIs, methods written in C language, and so on. In this case, the declaration must be static. At


the same time, the extern keyword can also define an external assembly alias, making it possible to refer to different versions of the same component from a single assembly.


The following is a simple example rewritten from MSDN, calling the system winmm.DLL to play wav files:


//Statement of system API calls
        [System.Runtime.InteropServices.DllImport("winmm.DLL", EntryPoint = "PlaySound", SetLastError = true)]
        public static extern void PlaySound(string path,System.IntPtr hMod,PlaySoundFlags flags);


//call this method


    string path = @"c:\111.wav";
            try
            {
                PlaySound(path, new System.IntPtr(), PlaySoundFlags.SND_SYNC);
            }
            catch (Exception ex)
            {
                throw (ex);
            } 


C# class for reading and writing ini files, call the api in kernel32.dll: WritePrivateProfileString, GetPrivateProfileString


using System .Runtime.InteropServices;


using System.Text; 


namespace INIFile


{


     /// <summary>


     /// Classes for reading and writing ini files


     /// Call two APIs in kernel32.dll: WritePrivateProfileString and GetPrivateProfileString to implement the ini file read and write.


     ///


     /// The INI file is a text file,


     /// consists of several sections,


     /// under each parenthesized title,


     /// are several keywords (key) and their corresponding values ​​(value)


     /// 


  ///[Section]


  ///Key=value


     ///


     /// </summary>


     public class IniFile


     {


         // / <summary>


         /// ini file name (with path)


         /// </summary>


         public string filePath; 


          //declare API functions for reading and writing INI files


         [DllImport("kernel32")] 


         private static extern long WritePrivateProfileString(string section,string key,string val,string filePath);
 


         [DllImport("kernel32")]


         private  static  extern  int  GetPrivateProfileString(string  section,string  key,string  def,StringBuilder  retVal,int  size,string  filePath);


 
         ///  <summary>


         ///  类的构造函数


         ///  </summary>


         ///  <param  name="INIPath">INI文件名</param> 


         public  IniFile(string  INIPath)   


         { 


              filePath  =  INIPath; 


         }


 
         ///  <summary>


         ///   写INI文件


         ///  </summary>


         ///  <param  name="Section">Section</param>


         ///  <param  name="Key">Key</param>


         ///  <param  name="value">value</param>
         public  void  WriteInivalue(string  Section,string  Key,string  value)   
         {     


              WritePrivateProfileString(Section,Key,value,this.filePath); 


         }


         ///  <summary>


         ///    读取INI文件指定部分


         ///  </summary>


         ///  <param  name="Section">Section</param>


         ///  <param  name="Key">Key</param>


         ///  <returns>String</returns> 


         public  string  ReadInivalue(string  Section,string  Key) 


         {   


              StringBuilder  temp  =  new  StringBuilder(255);


              int  i  =  GetPrivateProfileString(Section,Key,"",temp,255,this.filePath); 


              return  temp.ToString();


         } 


     } 


}
========

Interoperate with unmanaged code

https://msdn.microsoft.com/en-us/library/sd10k43k(v=vs.80).aspx
.NET Framework 2.0 Other versions 
Microsoft .NET Framework will facilitate integration with COM components, COM+ services, external type libraries and many Interoperability of operating system services. There are differences in data types, method signatures, and error handling mechanisms between managed and unmanaged object models. To simplify interoperability and portability between .NET Framework components and unmanaged code, the common language runtime hides the differences between these two object models from clients and servers.
Code that executes under the control of the runtime is called managed code. In contrast, code that runs outside of the runtime is called unmanaged code. COM components, ActiveX interfaces, and Win32 API functions are examples of unmanaged code.
In This Section Interoperating
with Unmanaged Code Help Topics
Provides links to all help topics found in the conceptual documentation on interoperating with unmanaged code.
Exposing COM Components to the .NET Framework
Describes how to use COM components from .NET-based applications.
Exposing .NET Framework Components to COM
Describes how to use .NET-based components from COM applications.
Using Unmanaged DLL Functions
Describes how to use Platform Invoke to call unmanaged DLL functions.
Design Considerations for Interoperability
Provides tips for writing integrated COM components.
Interoperable Marshaling
Describes how to marshal COM Interop and platform calls.
HOWTO: Mapping HRESULTs and Exceptions
Describes the mapping between exceptions and HRESULTs.
Interop Using Generic Types
Describes the behavior of generic types when used for COM interop.
Related Sections
Advanced Development Techniques
Provides links to more information about advanced development tasks and techniques in the .NET Framework.
========

advanced development techniques

https://msdn.microsoft.com/en-us/library/a493kdy6(v=vs.80).aspx
This topic provides links to information about complex development tasks and techniques in the .NET Framework.
In This Section
Administration
Provides information about using directory services and Windows Management Instrumentation (WMI).
Component Authoring for the Design Environment
Describes how to create custom components and extend design-time support.
Asynchronous Programming Design Patterns
Discusses asynchronous programming features in the .NET Framework.
Dynamic source code generation and compilation
Interprets the Code Document Object Model (CodeDOM), which enables output of source code in multiple programming languages.
Emit Dynamic Methods and Assemblies
Describes a set of managed types in the System.Reflection.Emit namespace that allow a compiler or tool to emit metadata and Microsoft Intermediate Language (MSIL) at runtime, or to generate them on disk Portable Executable (PE) files.
Garbage Collection
Discusses how the garbage collector manages memory and how you can program to use memory more efficiently.
Hosting the Common Language Runtime
Explains runtime hosting concepts, loading the runtime into a process, creating an application domain within that process, and loading and executing user code.
Interoperability
Describes the interoperability services provided by the common language runtime. Also provides links to information on integrating COM components into .NET Framework applications.
Network Programming
Demonstrates how to use Internet access classes to implement Web-based and Internet-based applications.
Reflection
Explains how to access type information at runtime by using reflection.
Reliability
Describes the use of reliability-oriented properties such as HPA and ReliabilityContract, and discusses best practices for writing reliable code.
Remote Objects
Describes the various communication methods provided in the .NET Framework for remote communications.
Serialization
Discusses XML serialization.
Managed Threading
Explains runtime support for processing and how to program using various synchronization techniques.
Writing Service Components
Describes how to configure and register service components to access COM+ services.
Refer to
System.Reflection.Emit
to illustrate the main functions of the Emit namespace.
Related Sections
Core Development Techniques
Provides links to information about standard application development tasks in the .NET Framework.
Security in the .NET Framework
Provides links to information about classes and services in the .NET Framework that can help secure application development.
========

Guess you like

Origin blog.csdn.net/bcbobo21cn/article/details/70477626