Search code examples
c#.netvisual-studio-2010visual-c++c++-cli

interacting between a C# project and C++ project in same solution


I have a windows forms app written in C++/cli. I want to extend this app with some new forms and I'd like to create them in C# in a separate project.

Is it possible to simply add a C# project to a solution that has the C++ project and the two will interact? By interaction, I mean that, say, a button clicked on a form written in the c# project will be able to call methods in the c++ project. Asked perhaps in a different way, can an object in the C# project reference an object in the c++ project?


Solution

  • Yes. A C++/CLI application will be able to interface with a C# application, in one of two ways:

    If you are using CLI extensions (which from your post it sounds like it), you will be able to write code using the new object references:

    Managed objects: System::String^ myString (in C++) is the same as string myString in C# Managed refs: System::String% myString is equivalent to ref string myString.

    If you want to use C++ native types, then you will have to use P/Invoke, but that's an entirely different category. For what you want to do, just add the C++ project as a reference to your C# project, write a publicly-visible class in C++ using managed types, and then compile. Your project should then be visible to your C# class in whatever namespace you chose for the C++ class.

    Oh, and if you need to allocate managed objects through C++, you will need to use gcnew instead of new.