Consuming C# dll from unmanaged C++ exe; StringCollection

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have a case where a C# dll is being consumed by an unmanaged C++
executable. One of the dll methods returns a StringCollection object. What
are the requirements for the C++ executable in terms of .h, .tlb files to be
included/imported, and the syntax for consuming the StringCollection object?

TIA.
 
eSapient said:
I have a case where a C# dll is being consumed by an unmanaged C++
executable. One of the dll methods returns a StringCollection object. What
are the requirements for the C++ executable in terms of .h, .tlb files to
be
included/imported, and the syntax for consuming the StringCollection
object?

You can use .NET via COM, see "Runtime Callable Wrapper". However that
might not be the easiest way to go.

Is the .dll a hard dependency (exe can't work without it) or a soft
dependency (lose some features but press forward)?

If it is a hard dependency, then your exe is actually dependent on the .NET
framework (exe needs dll needs framework). In that case, see if your exe
works correctly when built with /clr.
 
I created a .NET class library with the following C# code:

using System;
using System.Runtime.InteropServices;
using System.Collections.Specialized;

namespace ClassLibrary3
{
[GuidAttribute("6F66DEAB-1BCF-4ce4-AB06-D298BA2B56CA")]
public class MyClass : IMyClass
{
public MyClass()
{}

void IMyClass.MyMethod(out StringCollection strings)
{
strings = new StringCollection();
strings.Add("First string");
strings.Add("Second string");
}
}

[GuidAttribute("F26D63B9-C3A8-4f1a-9B17-1C441DE58EAF")]
public interface IMyClass
{
void MyMethod(out StringCollection strings);
}
}

I registered this project for COM Interop.

I then created a console application in VC++, where I added a reference to
the class library project (both projects are in the same solution). I am not
very familiar with COM programming using C++. My intention is to consume the
class library above in unmanaged C++. I added the following code in the
console application, but it is incomplete since I don't know how to go about
it.

#include "stdafx.h"

#import "mscorlib.tlb"
//#import "..\ClassLibrary3\bin\Debug\ClassLibrary3.tlb"

#using <mscorlib.dll>

using namespace System;
using namespace System::Collections::Specialized;
//using namespace ClassLibrary3;

int _tmain()
{
::CoInitialize(0);
ClassLibrary3::IMyClassPtr pIMyClass(__uuidof(ClassLibrary3::MyClass));
// pIMyClass.MyMethod();

return 0;
}

Can somebody help me and show me how to consume the .NET class?

Thanks in advance.
 
Back
Top