Question

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!

Was it helpful?

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();
...

OTHER TIPS

Writing a COM should not be difficult:

namespace CPersoanaNameSpace
{
   [Guid("8578CEB3-6C04-4FC2-BB80-FB371A9F")]
   [ComVisible(true)]
   public interface ICPersoanaCOM
   {

      [DispId(1)]
      void Name(out string name);

      [DispId(2)]
      void Profession(out string profession);

      [DispId(3)]
      void Age(out int age);
    }
    }

Implement the interface

   [ComVisible(true)]
   [Guid("6BE742E0-CDEC-493A-B755-D5Crtr5w6A545"),
   public class CPersoana: ICPersoanaCOM
   {
//...
   }

Then using it in C++:

//Import tlb
#import "path to tlb\Persoana.tlb"  named_guids raw_interfaces_only
using namespace System;

int main(array<System::String ^> ^args)
{

   CoInitialize(NULL);   //Initialize all COM Components


   CPersoanaNameSpace::CPersoanaCOMPtr objPtr;

  HRESULT hRes =  objPtr.CreateInstance(CPersoanaNameSpace::CLSID_CPersoana);
  if (hRes == S_OK)
  {
      BSTR LocName;
      objPtr->Name(&LocName);
      }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top