简体   繁体   中英

Returning Managed C# List to Unmanaged C++ code

I have a C# dll ( for which register for COM interop option is set).

This C# dll has the below interface and class

interface IMyInterface
{
    bool IsNameExists(string name);
    List<string> GetNameList();
} 

public class MyClass : IMyInterface
{

    public bool IsNameExists(string name)
    {
        //DO Something

    }
    public List<string> GetNameList()
    {

        // DO something
    }

} 

I need to call the methods IsNameExists and GetNameList from unmanaged C++.

#import "..\..\ProdCon\bin\ProdCon.tlb" raw_interfaces_only

   void main()
   {    
        HRESULT hr =::CoInitialize(NULL);
        IMyInterface pIMyInterface(__uuidof(MyClass));

        VARIANT_BOOL bRet = FALSE;

        BSTR bstrName = ::SysAllocString(_T("RAJESH"));
        hr =  pIMyInterface->IsNameExists(bstrName,&bRet);

    }

So I created COM object as above and called the IsNameExists mehtod without any issue.

Since GetNameList method returns list, I am getting the below warning

'MyDll.IMyInterface.GetNameList(#0), MyDll'. Warning: Type library exporter encountered a generic type instance in a signature. Generic code may not be exported to COM.

Please help me how to return C# list to unmanaged C++ code. So that unmanaged C++ code can use this list.

'Generic code may not be exported to COM.' => hence its the type parameter string in public List GetNameList(). Thus essentially you need access to a non-generic c# method to get the data.

If you have control of the MyClass codebase you could (for example) add a:

public string[] GetNameArray()
{
   return GetNameList.ToArray();
}

If not then you'll need to write a proxy/wrapper class to do something similar to the above and expose that via COM, either as a one off or a 'general' methodology using reflection say.

See for example http://weblog.west-wind.com/posts/2007/Jul/10/Generics-and-COM-Interop-dont-mix

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM