Tuesday, July 27, 2010

How to introduce the Interop.. with example

After searching everywhere, I bet you I never found the implementation of the INTPTR, all thru the internet.
I'm trying to put it here so that, you can get all the stuff you required in implementation, in one place.

COM server's function should be called from the C#, as follows
1. Put  System.Runtime.InteropServices where you want to call the function.

Here, I would like to start from start from the basic defination of BSTR and then we move on advanced explaination and implementation details.



What is BSTR?
BSTR is a pointer to Unicode string. you can say it's a string defined by Ole Automation for which memory is allocated by the system when users call SysAllocString/SysAllocStringLen.

Allocated memory should get freed by the call  SysFreeString.
Size of the BSTR is stored at 4 bytes before the actual BSTR pointer returned by  SysAllocString/SysAllocStringLen on both 32bit and 64 bit platform.

Marshaling BSTR in  Interop....
Marshal a BSTR by using MarshalAsAttribute,

Default Marshaling for Strings
Strings are marshaled as a COM-style BSTR type or as a character array terminating in a null reference (Nothing in Visual Basic). The characters within the string can be marshaled as Unicode or ANSI, or in a platform-dependent manner (Unicode on Microsoft Windows NT, Windows 2000, and Windows XP; ANSI on Windows 98 and Windows Millennium Edition (Windows Me).

This topic provides the following information on marshaling string types:
--Strings Used in Interfaces
--Strings Used in Platform Invoke
--Strings Used in Structures
--Fixed-Length String Buffers

Strings Used in Interfaces

The marshaling options for the string data type when marshaled as a method argument to unmanaged code. The MarshalAsAttribute attribute provides several UnmanagedType enumeration values to marshal strings to COM interfaces.

Enumeration type                                Description of unmanaged format
UnmanagedType.BStr (default)           A COM-style BSTR with a prefixed length and Unicode characters.
UnmanagedType.LPStr                      A pointer to a null-terminated array of ANSI characters.
UnmanagedType.LPWStr                  A pointer to a null-terminated array of Unicode characters.

This implementation is  applies to strings. However, for StringBuilder, the only options allowed are UnmanagedType.LPStr and UnmanagedType.LPWStr.

Please find the example ( in C++)

public interface IStringWorker {
void PassString1(String s);
void PassString2([MarshalAs(UnmanagedType.BStr)]String s);
void PassString3([MarshalAs(UnmanagedType.LPStr)]String s);
void PassString4([MarshalAs(UnmanagedType.LPWStr)]String s);
void PassStringRef1(ref String s);
void PassStringRef2([MarshalAs(UnmanagedType.BStr)]ref String s);
void PassStringRef3([MarshalAs(UnmanagedType.LPStr)]ref String s);
void PassStringRef4([MarshalAs(UnmanagedType.LPWStr)]ref String s);
) ;

The corrosponding code shows in corresponding interface described in a type library.

[…]

Interface IStringWorker : IDispatch
{ 
 HRESULT PassString1([in] BSTR s);
 HRESULT PassString2([in] BSTR s);
 HRESULT PassString3([in] LPStr s);
 HRESULT PassString4([in] LPWStr s);
 HRESULT PassStringRef1([in, out] BSTR *s);
 HRESULT PassStringRef2([in, out] BSTR *s);
 HRESULT PassStringRef3([in, out] LPStr *s);
 HRESULT PassStringRef4([in, out] LPWStr *s);
 );


Strings Used in Platform Invoke
--------------------------------------------------------------------------------
Platform invoke copies string arguments, converting from the .NET Framework format (Unicode) to the platform unmanaged format. Strings are immutable and are not copied back from unmanaged memory to managed memory when the call returns.

The following table lists the marshaling options for strings when marshaled as a method argument of a platform invoke call. The MarshalAsAttribute attribute provides several UnmanagedType enumeration values to marshal strings.

Enumeration type                                     Description of unmanaged format

UnmanagedType.AnsiBStr              COM-style BSTR with a prefixed length and ANSI characters.
UnmanagedType.BStr                     COM-style BSTR with a prefixed length and Unicode characters.
UnmanagedType.LPStr                   Pointer to a null-terminated array of ANSI characters.
UnmanagedType.LPTStr (default)    Pointer to a null-terminated array of platform-dependent  characters.
UnmanagedType.LPWStr                A pointer to a null-terminated array of Unicode characters.
UnmanagedType.TBStr            COM-style BSTR with a prefixed length & platform-dependent characters.
VBByRefStr                             A value that enables Visual Basic .NET to change a string in unmanaged code, and have the results reflected in managed code. This value is supported only for platform invoke.

Above implemetation applies to strings. However, for StringBuilder, the only options allowed are LPStr, LPTStr, and LPWStr.

Example :
The following type definition shows the correct use of MarshalAsAttribute for platform invoke calls.

C++ Does not support this implementation.
Taking the example of C#
class StringLibAPI {
[DllImport("StringLib.Dll")]
public static extern void PassLPStr([MarshalAs(UnmanagedType.LPStr)] String s);

[DllImport("StringLib.Dll")]
public static extern void  PassLPWStr([MarshalAs(UnmanagedType.LPWStr)]String s);

[DllImport("StringLib.Dll")]
public static extern void  PassLPTStr([MarshalAs(UnmanagedType.LPTStr)]String s);

[DllImport("StringLib.Dll")]
public static extern void PassBStr([MarshalAs(UnmanagedType.BStr)] String s);

[DllImport("StringLib.Dll")]
public static extern void  PassAnsiBStr([MarshalAs(UnmanagedType.AnsiBStr)]String s);

[DllImport("StringLib.Dll")]
public static extern void PassTBStr([MarshalAs(UnmanagedType.TBStr)] String s);
}

Strings Used in Structures
-------------------------------------------------------------------------------
Strings are valid members of structures; however, StringBuilder buffers are invalid in structures. The following table shows the marshaling options for the string data type when the type is marshaled as a field. The MarshalAsAttribute attribute provides several UnmanagedType enumeration values to marshal strings to a field.

Enumeration type                                 Description of unmanaged format
UnmanagedType.BStr                A COM-style BSTR with a prefixed length and Unicode characters.
UnmanagedType.LPStr              A pointer to a null-terminated array of ANSI characters.
UnmanagedType.LPTStr            A pointer to a null-terminated array of platform-dependent characters.
UnmanagedType.LPWStr          A pointer to a null-terminated array of Unicode characters.
UnmanagedType.ByValTStr      Fixed-length array of characters; the array's type is determined by the character set of the containing structure.

 The ByValTStr type is used for inline, fixed-length character arrays that appear within a structure.
Other types apply to string references contained within structures that contain pointers to strings.

The CharSet argument of the StructLayoutAttribute attribute that is applied to the containing structure determines the character format of strings in structures. The following example structures contain string references and inline strings, as well as ANSI, Unicode, and platform-dependent characters.

Type Library Representation

struct StringInfoA
{
 char * f1;
 char f2[256];
 };

struct StringInfoW
{  
     WCHAR * f1;
     WCHAR f2[256];
      BSTR f3;
};

struct StringInfoT
{
      TCHAR * f1;
      TCHAR f2[256];
 };

Now have a look of an example :
This implementation also not present in C++
So,  I took the C# example that shows how to use the MarshalAsAttribute attribute to define the same structure in different formats.

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]

struct StringInfoA
{ 
 [MarshalAs(UnmanagedType.LPStr)] public String f1;
 [MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)] public String f2;
}

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]

struct StringInfoW
{
   [MarshalAs(UnmanagedType.LPWStr)] public String f1;
   [MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)] public String f2;
   [MarshalAs(UnmanagedType.BStr)] public String f3;
}

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
struct StringInfoT
{ 
     [MarshalAs(UnmanagedType.LPTStr)] public String f1;
      [MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)] public String f2;
}


Fixed-Length String Buffers
-------------------------------------------------------------------------------
In some circumstances, a fixed-length character buffer must be passed into unmanaged code to be manipulated. Simply passing a string does not work in this case because the callee cannot modify the contents of the passed buffer. Even if the string is passed by reference, there is no way to initialize the buffer to a given size.

The solution is to pass a StringBuilder buffer as the argument instead of a string. A StringBuilder can be dereferenced and modified by the callee, provided it does not exceed the capacity of the StringBuilder. It can also be initialized to a fixed length. For example, if you initialize a StringBuilder buffer to a capacity of N, the marshaler provides a buffer of size (N+1) characters. The +1 accounts for the fact that the unmanaged string has a null terminator while StringBuilder does not.

For example, the Microsoft Win32 API GetWindowText function (defined in Windows.h) is a fixed-length character buffer that must be passed into unmanaged code to be manipulated. LpString points to a caller-allocated buffer of size nMaxCount. The caller is expected to allocate the buffer and set the nMaxCount argument to the size of the allocated buffer. The following code shows the GetWindowText function declaration as defined in Windows.h.

int GetWindowText(  HWND hWnd, // Handle to window or control.
                                  LPTStr lpString, // Text buffer.
                                  int nMaxCount // Maximum number of characters to copy.
                                 );

A StringBuilder can be dereferenced and modified by the callee, provided it does not exceed the capacity of the StringBuilder. The following code example demonstrates how StringBuilder can be initialized to a fixed length.

Taking the Example:
public class Win32API { [DllImport("User32.Dll")]

public static extern void GetWindowText(int h, StringBuilder s,  int nMaxCount);

}

public class Window { internal int h; // Internal handle to Window.

public String GetText()
{ 
   StringBuilder sb = new StringBuilder(256);
    Win32API.GetWindowText(h, sb, sb.Capacity + 1);
     return sb.ToString();
}

}
(refer http://msdn2.microsoft.com/en-us/library/s9ts558h.aspx)
Passing  BSTR as an In/Out parameter?
Now the important and thing to notice is ho wto pass BSTR as an In\Out parameter.

Note down the sample which demostrate,  how to pass strings as In/Out parameters to unmanaged functions that expect a string (LPSTR) as a function parameter. Further, it shows how to use a string returned from an unmanaged method in the special case where the caller is not supposed to free memory allocated for the string.

This sample platform invokes two native Win32 functions exported from Kernel32.dll:
GetSystemDirectory                Retrieves the path of the system directory.
GetCommandLine                   Retrieves the command-line string for the current process.

The LibWrap class contains a managed prototypes for the unmanaged functions, which are called from Main in the console application. The CharSet field is set so that platform invoke can choose between ANSI and Unicode formats at run time, based on the target platform. For more information about this field, see Specifying a Character Set.

The GetSystemDirectory prototype method substitutes a StringBuilder buffer for the unmanaged LPSTR type. The buffer size remains fixed. To accommodate the requirements of the original function, GetSystemDirectory passes the buffer size variable as the second argument. A StringBuilder buffer, rather than a string, replaces the LPTSTR type in the declaration. Unlike strings, which are immutable, StringBuilder buffers can be changed.

The native GetCommandLine function returns a pointer to a buffer allocated and owned by the operating system. When marshaling strings as return types, the interop marshaler assumes it must free the memory that the original LPTSTR type pointed to by the function. To prevent the marshaler from automatically reclaiming this memory, the managed GetCommandLine prototype returns an IntPtr type instead of a string. The PtrToStringAuto method copies the unmanaged LPSTR type to a managed string object, widening the character format, if required.

Declaring Prototypes

public ref class LibWrap
{
    public:
     [DllImport("Kernel32.dll", CharSet=CharSet::Auto)]
     static int GetSystemDirectory(StringBuilder^  sysDirBuffer, int size);
    
     [DllImport("Kernel32.dll", CharSet=CharSet::Auto)]
     static IntPtr GetCommandLine();
};

Calling Functions

public ref class App

{
   public:
   static void Main()
          {
                  // Call GetSystemDirectory.
                  StringBuilder^ sysDirBuffer = gcnew StringBuilder(256);
                   LibWrap::GetSystemDirectory(sysDirBuffer, sysDirBuffer->Capacity);
               
                   // ...
                   // Call GetCommandLine.
                    IntPtr cmdLineStr = LibWrap::GetCommandLine();
                    String^ commandLine = Marshal::PtrToStringAuto(cmdLineStr);
             }
};

Inspired By : refer to : http://msdn2.microsoft.com/en-us/library/x3txb6xc.aspx .

Umanaged Plateform Invoke call:

How P-Invoke works.
Let us discuss how P\Invoke works later we'll see it by example. I bet you'll not find that kind of explanation, else where, apart from the link I'm refering to you in this article.

How P/Invoke Works 
P/Invoke, as you should be aware that  relies on the DllImport attribute from the System.Runtime.InteropServices namespace. The DllImport attribute specifies that the target method is an export from an unmanaged shared library such as the Win32 API. In the simple case you've seen here, all you need to do is declare the name of the DLL from which you're importing the call and the parameters of the call itself. 

The compiler emits the DllImport information directly into the MSIL (Microsoft Intermediate Language) executable file format. The runtime recognizes this information and uses the Marshal class of the System. Runtime.InteropServices namespace to get the parameter and return data across the boundary between managed and unmanaged code. The runtime is actually quite clever about doing the right thing when marshaling the data back and forth between managed and unmanaged types. It copies data when it needs to, pins managed data reference types in memory so that they can be used by unmanaged code, and when needed, converts strings from ANSI to Unicode or vice-versa. 

Sometimes, merely declaring a DLL name and function prototype does not suffice to describe the necessary behavior for marshalling. For such cases, the DllImport attribute has additional fields to specify the imported function's calling convention and character set, among others. You can also use the MarshalAs attribute to control how specific parameters are passed, and the StructLayout attribute to define structures for marshaling. I'll discuss those in Part 2 of this article series. 


We've done with theoretical part, now let's have a look in a detailed example;
with explanation. 

__declspec(dllexport)
void functionInCOM(BSTR *bstrfun)
{
      *bstrfun= SysAllocString(L"hello");
}

Then, the corresponding managed call should be(using C# example)



 functionInCOM(ref goPtr); //get the bstr
 String str = Marshal.PtrToStringBSTR(goPtr); //convert it to the managed string
 Console.WriteLine(str ); //test we have got it
 // now free the unmanaged BSTR. Do not forget this or there will be leaks.
  Marshal.FreeBSTR(goPtr);
}


Also try:  More Useful stuff on this topic :

http://journeyallover.blogspot.com/2010/07/what-is-difference-between-com-dll.html
http://journeyallover.blogspot.com/2010/07/use-interopmarshalling-in-c.html
http://journeyallover.blogspot.com/2010/07/how-to-introduce-interop-with-example.html
http://journeyallover.blogspot.com/2010/07/usesconversion.html
http://journeyallover.blogspot.com/2010/07/marshaling-bstrs-in-cominterop.html
http://journeyallover.blogspot.com/2010/07/what-is-intptr.html
http://journeyallover.blogspot.com/2010/07/interop-marshaling-overview.html
http://journeyallover.blogspot.com/2010/07/interop-cc-issues.html


What happens, though, if the API you're calling does something really weird?
Refer:  http://www.devx.com/dotnet/Article/6990/1954

You dont need to visit the refered linked :
http://www.codeproject.com/Articles/66243/Marshaling-with-Csharp-Chapter-3-Marshaling-Compou.aspx
http://stackoverflow.com/questions/1300122/marshalling-bstrs-from-c-to-c-with-com-interop
http://msdn.microsoft.com/en-us/library/sd10k43k(vs.71).aspx
http://msdn.microsoft.com/en-us/library/f1cf4kkz(v=vs.71).aspx
http://msdn.microsoft.com/en-us/library/x3txb6xc(v=vs.71).aspx
http://www.codeproject.com/KB/cs/unmanaged_memory_pointers.aspx

How to get IntPtr from byte[] in C#

http://stackoverflow.com/questions/537573/how-to-get-intptr-from-byte-in-c


Default Marshaling for Strings
http://msdn.microsoft.com/en-us/library/s9ts558h.aspx

Interoperating with Unmanaged Code
http://msdn.microsoft.com/en-us/library/sd10k43k.aspx
[DllImport("My.dll")]
        extern static void functionInCOM(out IntPtr goPtr);



      IntPtr goPtr= IntPtr.Zero;

static void Main(string[] args)

{

Monday, July 26, 2010

Buffers Sample

Buffers Sample
This sample shows how to pass strings as In/Out parameters to unmanaged functions that expect a string (LPSTR) as a function parameter. Further, it shows how to use a string returned from an unmanaged method in the special case where the caller is not supposed to free memory allocated for the string.

Follow MSDN.

USES_CONVERSION.

In ATL there are some helper macros defined such as W2A() which is used to convert widechar to ansi and A2W which is used to convert ansi to WideChar. Before using this macros you should initialize the conversion by calling USES_CONVERSION. See the code snippet below.
#include "atlconv.h"
...

// Ansi string.
char* ptrStr = "Example";

// Unicode string.
wchar_t* pUStr = 0;

// Use this macro for Initializing the conversion.
// Actually, some member variable initialization deep inside.
USES_CONVERSION;

// Convert Ansi to Unicode.
pUStr = A2W( ptrStr );

// Convert Unicode to Ansi.
ptrStr = W2A( pUStr );

Marshaling BSTRs in COM/Interop

After struggling so many days for a right implementation after all I got a right approach to deal with it.
Actually I'd completed with the implementation ( calling BSTR from C# client), but at the peer-review , we discussed about the potential memory leak.

After google so many things, MSDN is not having so much collective information and example. 
the best thing I found, what is want to share all of you guys...


http://www.codeproject.com/Articles/66243/Marshaling-with-Csharp-Chapter-3-Marshaling-Compou.aspx
Marshaling BSTRs in COM/Interop or P/Invoke

So I came to follow below links.
http://social.msdn.microsoft.com/Forums/en-US/clr/thread/9a4e8bbb-efbd-4a90-9549-4e1795198800

http://dotnet.itags.org/dotnet-c-sharp/86388/

http://objectmix.com/dotnet/103378-how-return-string-array-com-c.html

http://objectmix.com/dotnet/257081-marshaling-array-into-com-server-ok-but-cant-return-array-invalid-procedure-call-argument.html

http://stackoverflow.com/questions/1300122/marshalling-bstrs-from-c-to-c-with-com-interop
Infact all are help ful.

http://www.codeproject.com/KB/COM/binbstr.aspx
http://msdn.microsoft.com/en-us/library/aa645736(VS.71).aspx



Looking for a sample code:
http://msdn.microsoft.com/en-us/library/aa664431(v=VS.71).aspx

If you are a VB developer :
http://objectmix.com/dotnet/102955-problem-passing-string-bstr-string-c-dll-nullreference-exception.html


COM Interop is causing a horrible CLR crash


http://bytes.com/topic/c-sharp/answers/248396-com-interop-causing-horrible-clr-crash

MONO
Mono 1.0 and Mono 1.1.xx do not have support for COM, it is a known missing feature of Mono. Initial work has begun on supporting MS COM on Windows. The long term goal is to support a variety of unmanaged component technologies including MS COM, XPCOM, and UNO.
http://www.mono-project.com/COM_Interop

Sunday, July 25, 2010

What is IntPtr???

The IntPtr type is designed to be an integer whose size is platform-specific. That is, an instance of this type is expected to be 32-bits on 32-bit hardware and operating systems, and 64-bits on 64-bit hardware and operating systems.
The IntPtr type can be used by languages that support pointers, and as a common means of referring to data between languages that do and do not support pointers.
IntPtr objects can also be used to hold handles. For example, instances of IntPtr are used extensively in the System.IO.FileStream class to hold file handles.
The IntPtr type is CLS-compliant, while the UIntPtr type is not. Only the IntPtr type is used in the common language runtime. The UIntPtrtype is provided mostly to maintain architectural symmetry with the IntPtr type.


A platform-specific type that is used to represent a pointer or a handle.

The IntPtr type is designed to be an integer whose size is platform-specific. That is, an instance of this type is expected to be 32-bits on 32-bit hardware and operating systems, and 64-bits on 64-bit hardware and operating systems.
The IntPtr type can be used by languages that support pointers, and as a common means of referring to data between languages that do and do not support pointers.

Download the sample by :
http://cid-fd3332cdd86da8fa.skydrive.live.com/self.aspx/Public/TestinIntPtr.rar

refer to MSDN.
http://msdn.microsoft.com/en-us/library/system.intptr(VS.71).aspx

Interop Marshaling Overview

Interop Marshaling Overview


Most data types have common representations in both managed and unmanaged memory. The interop marshaler handles these types for you. Other types can be ambiguous or not represented at all in managed memory.
An ambiguous type can have either multiple unmanaged representations that map to a single managed type, or missing type information, such as the size of an array. For ambiguous types, the marshaler provides a default representation and alternative representations, where multiple representations exist. You can supply explicit instructions to the marshaler on how it is to marshal an ambiguous type.
This topic begins with a review of the platform invoke and COM interop programming models. It describes how interop marshaling integrates with COM marshaling in the subtopic Marshaling and COM Apartments. It then describes how the marshaler performs in a distributed environment in the subtopic Marshaling Remote Calls.

Platform Invoke and COM Interop Models

The common language runtime provides two mechanisms for interoperating with unmanaged code:
  • Platform invoke, which enables managed code to call functions exported from an unmanaged library.
  • COM interop, which enables managed code to interact with COM objects through interfaces.
Both platform invoke and COM interop use interop marshaling to accurately move method arguments between caller and callee and back, if required. As the following illustration shows, except when callback functions are involved, a platform invoke method call flows from managed to unmanaged code, and never the other way. Even though platform invoke calls can flow only from managed to unmanaged code, data can flow in both directions as In or Out parameters. COM interop method calls can flow in either direction.
Platform invoke and COM interop call flow
At the lowest level, both mechanisms use the same interop marshaling service; however, certain data types are supported exclusively by COM interop or platform invoke. For details, see Default Marshaling Behavior.

Marshaling and COM Apartments

The interop marshaler marshals data between the common language runtime heap and the unmanaged heap. Marshaling occurs whenever the caller and callee cannot operate on the same instance of data. The interop marshaler makes it possible for both the caller and callee to appear to be operating on the same data even though the caller and callee have their own copy of the data.
COM also has a marshaler that marshals data between COM apartments or different COM processes. When calling between managed and unmanaged code within the same COM apartment, the interop marshaler is the only marshaler involved. When calling between managed code and unmanaged code in a different COM apartment or a different process, both the interop marshaler and the COM marshaler are involved.

COM Client and .NET Server

An exported managed server with a type library registered by the Assembly Registration tool (Regasm.exe) has a ThreadingModel registry entry set to Both. This value indicates that the server can be activated in a single-threaded apartment (STA) or a multithreaded apartment (MTA). The server object is created in the same apartment as its caller, as shown in the following table.
COM client.NET serverMarshaling requirements
STABoth becomes STA.Same-apartment marshaling.
MTABoth becomes MTA.Same-apartment marshaling.
Because the client and server are in the same apartment, the interop marshaling service automatically handles all data marshaling. The following illustration shows the interop marshaling service operating between managed and unmanaged heaps within the same COM-style apartment.
Same-apartment marshaling process
If you plan to export a managed server, be aware that the COM client determines the apartment of the server. A managed server called by a COM client initialized in an MTA must ensure thread safety.

.NET Client and COM Server

The default setting for .NET client apartments is MTA; however, the application type of the .NET client can change the default setting. For example, a Visual Basic .NET client apartment setting is STA. You can use the STAThreadAttribute, the MTAThreadAttribute, theThread.ApartmentState property, or the Page.AspCompatMode property to examine and change the apartment setting of a managed client.
The author of the component sets the thread affinity of a COM server. The following table shows the combinations of apartment settings for .NET clients and COM servers. It also shows the resulting marshaling requirements for the combinations.
.NET clientCOM serverMarshaling requirements
MTA (default)MTASTAInterop marshaling.Interop and COM marshaling.
STAMTASTAInterop and COM marshaling.Interop marshaling.
When a managed client and unmanaged server are in the same apartment, the interop marshaling service handles all data marshaling. However, when client and server are initialized in different apartments, COM marshaling is also required. The following illustration shows the elements of a cross-apartment call.
Cross-apartment call between a .NET client and COM object
For cross-apartment marshaling, you can do the following:
  • Accept the overhead of the cross-apartment marshaling, which is noticeable only when there are many calls across the boundary. You must register the type library of the COM component for calls to successfully cross the apartment boundary.
  • Alter the main thread by setting the client thread to STA or MTA. For example, if your C# client calls many STA COM components, you can avoid cross-apartment marshaling by setting the main thread to STA.
    Note   Once the thread of a C# client is set to STA, calls to MTA COM components will require cross-apartment marshaling.
For instructions on explicitly selecting an apartment model, see Managed and Unmanaged Threading.

Marshaling Remote Calls

As with cross-apartment marshaling, COM marshaling is involved in each call between managed and unmanaged code whenever the objects reside in separate processes. For example:
  • A COM client that invokes a managed server on a remote host uses DCOM.
  • A managed client that invokes a COM server on a remote host uses DCOM.
The following illustration shows how interop marshaling and COM marshaling provide communications channels across process and host boundaries.
Cross-process marshaling

Preserving Identity

The common language runtime preserves the identity of managed and unmanaged references. The following illustration shows the flow of direct unmanaged references (top row) and direct managed references (bottom row) across process and host boundaries.
Reference passing across process and host boundaries
In this illustration:
  • An unmanaged client gets a reference to a COM object from a managed object that gets this reference from a remote host. The remoting mechanism is DCOM.
  • A managed client gets a reference to a managed object from a COM object that gets this reference from a remote host. The remoting mechanism is DCOM.
    Note   The exported type library of the managed server must be registered.
The number of process boundaries between caller and callee is irrelevant; the same direct referencing occurs for in-process and out-of-process calls.

Managed Remoting

The runtime also provides managed remoting, which you can use to establish a communications channel between managed objects across process and host boundaries. Managed remoting can accommodate a firewall between the communicating components, as the following illustration shows.
Remote calls across firewalls using SOAP or the TcpChannel class
Some unmanaged calls can be channeled through SOAP, such as the calls between Serviced Components and COM.

Reference to
http://msdn.microsoft.com/en-us/library/eaw10et3(v=vs.71).aspx

InterOp .... C++\C# issues


C# interop keep throwing MemoryAccessViolation


I faced with interesting problem, think I should share with you all.
basically I'm a C++ programmer and working as beginner with C#.
I've to get the value from COM C++ component to the (C# as a client),
Here I got an interesting MSDN help.
Please go thru the link.

http://social.msdn.microsoft.com/Forums/en-US/clr/thread/9a4e8bbb-efbd-4a90-9549-4e1795198800

http://dotnet.itags.org/dotnet-c-sharp/86388/

http://objectmix.com/dotnet/103378-how-return-string-array-com-c.html

http://objectmix.com/dotnet/257081-marshaling-array-into-com-server-ok-but-cant-return-array-invalid-procedure-call-argument.html

http://stackoverflow.com/questions/1300122/marshalling-bstrs-from-c-to-c-with-com-interop

Health Benefits of Cashews

  Benefits of Cashews. Healthy food is an integral part of healthy body. Regular exercises such as Yoga and healthy diet is important to...