Search code examples
c#c++mfcunmanagedmanaged

Use C# managed app class in C++ unmanaged app


I have a project with this class written in C# that I use to serialize some data.

 [XmlType("CPersoane")]
 public class CPersoana
 {
        public CPersoana() { }

        [XmlElement("name")]
        public string Name { get; set; }

        [XmlElement("profession")]
        public string Profession{ get; set; }

        [XmlAttribute("age")]
        public int Age{ get; set; }

        //...
}

I also have another project in the same solution written C++ MFC (no CLR support) with a Dialog box with 3 text boxes.

How can I access the "CPersoana" class from C++ so that I can use "Name", "Profession" and "Age" with my text boxes?

Any help would be greatly appreciated!


Solution

  • Firstly, your c# project needs to be a DLL (Output Type = Class Library).

    Secondly, you cannot access c# code in unmanaged C++, your C++ project needs at least one source file that is compiled with /CLR where you can access your c# class.

    In that source file, you can write code like

    #using "MyCSharpProject.DLL"
    using namespace MyCSharpNamespace;
    ...
    gcroot<CPersoana^> pPersona = gcnew CPersoana();
    CString sFileName = <path to file>;
    pPersona->LoadFromFile(gcnew System::String(sFileName));
    // LoadFromFile would be a member function in the CPersoana class
    // like bool LoadFromFile(string sFileName)
    CString sName(pPersona->Name->ToString();
    ...