2

I've been writing a program in C++ and noticed there is a library in C# that someone else wrote that I would like to link in to my code.... but I'm not sure how to do that. Can someone suggest something? Doubt this matters, but I'm using Windows 7 with MSVC2010.

Thanks in advance!

Cenoc
  • 11,172
  • 21
  • 58
  • 92
  • 1
    What does the library do? Maybe there is a C++ library for that. – Khaled Alshaya Jun 12 '10 at 14:59
  • It's a voice recognition library, but I'd also just like to know the answer to this question for the future, regardless of whether is another library for this. – Cenoc Jun 12 '10 at 15:03

2 Answers2

6

You can try compiling your C++ program in C++/CLI mode. Then the compiler will produce a .NET executable which can create C# objects and use their methods.

C++/CLI is discussed here: C++/CLI

Pat Wallace
  • 743
  • 7
  • 12
  • 1
    +1. Note that if you do this though you'll have to mark your assembly as unsafe as marking your code as safe requires that there be no unmanaged code. – Billy ONeal Jun 12 '10 at 15:16
  • It sounds like that would require refactoring of the C# code? Is that the case? Also, can I compile other programs such as Qt with C++/CLI? – Cenoc Jun 12 '10 at 15:35
  • You shouldn't need to change anything on the C# side, as you can create and use .NET objects in C++/CLI, something like: `DotNetClass^ aClass = gcnew DotNetClass(); aClass->SomeMethod();` You would probably have trouble converting libraries such as QT into C++/CLI. However you can set individual files in a project to compile in C++/CLI mode and leave the others as normal C++. Visual Studio will manage the transition for you. This means you can create a C++/CLI wrapper around the .NET library, and keep the rest of the project in regular C++. – Pat Wallace Jun 14 '10 at 00:51
5

If you're familiar with COM you could access the .NET library through COM. If the library doesn't provide COM interop out of the box you could write a wrapper around it using C# and expose that through COM.

If you're going to pull in a .NET library you should be aware that it requires a .NET runtime which may take up valuable resources. If you ware building the application in C++ for performance reasons, maybe you're better off porting the parts of the library you need to C++.

Marnix van Valen
  • 13,265
  • 4
  • 47
  • 74