tags:

views:

462

answers:

3

Hi

i have tried returning a collection of objects from c# and access them usig c++ via COM but failed.I have tried for List ArrayList and IDictionary all and failed.

i have tried

http://stackoverflow.com/questions/1032060/how-to-return-a-collection-of-strings-from-c-to-c-via-com-interop also but not succeed.

can any body Help me

A: 

How about using an old-fashioned array?

public interface IManaged
{
    string[] ReturnArray();
}

public class Managed : IManaged
{
    public string[] ReturnArray()
    {
        return new string[] { "A", "B", "C" };
    }
}

Running tlbexp.exe with this .dll creates a .tlb with:

interface IManaged : IDispatch {
    [id(0x60020000)]
    HRESULT ReturnArray([out, retval] SAFEARRAY(BSTR)* pRetVal);
};

I have not tested using the .dll from native .exe, but it looks promising :)

Kei
A: 

It is normal that you cannot pass an object from c# to c++ or from c++ to c#. An object in c# is not like an object in c++. What you can pass from c# to c++ are types like bool, int, and char. Also, watch out for the size of types... for example a char in c# is a wchar_t in c++.

Partial
+2  A: 

@Partial, you raise an important point. You cannot pass a .NET "object" back to C++ (unless it's Managed C++) because .NET object semantics are not the same as C++ object semantics.

@Cute: you can, however, pass COM Interface Pointers. If you need your "traditional C++" code to talk to .NET objects, use COM Interfaces, not objects.

Make sure your object is marked as a COM object, and that you implement a suitable Interface that contains the methods that your C++ needs. Then, pass an array of the Interface references back to the C++ code. The C++ code should get a SafeArray of COM interface pointer, which it can manipulate with the usual COM semantics (AddRef(), etc.).

Euro Micelli
Cn u give me some piece of code to get idea.I Hav used IDictionary also a genric interface but filaed to get values in c++
Cute