Mixed management in C++

Povylas picture Povylas · Feb 14, 2012 · Viewed 8k times · Source

I have added a class to my program and tested it. I was really surprised that there was any real errors. Here is the code:

#pragma once
#include "Iingredient.h"
#include <string>
#include <vector>

using namespace std;

ref class Recipe{
private:
    string partsName;
    vector<Iingredient> ing;
public:
    Recipe(){}

};

And here are the errors:

Error 23 error C4368: cannot define 'partsName' as a member of managed 'Recipe': mixed types are not supported c:\users\user\documents\visual studio 2010\projects\smestras2_l1\Recipe.h 10 1 file2_L1

Error 24 error C4368: cannot define 'ing' as a member of managed 'Recipe': mixed types are not supported c:\users\user\documents\visual studio 2010\projects\smestras2_l1\Recipe.h 11 1 file2_L1

I googled a bit and found out that its about managed and unmanaged code. How to fix this? Is it related with manged and unmanaged code or not? if so how?

Answer

svick picture svick · Feb 14, 2012

I agree with others: you shouldn't use C++/CLI in most circumstances, you should use C# (or another "normal" managed language) for that (assuming you want to write a .Net application). C++/CLI is useful mostly in special circumstances, like interoperating between managed and unmanaged code.

If you're sure you want use C++/CLI, you can't put native classes into managed ones. But you can put pointers to native classes there:

ref class Recipe{
private:
    string* partsName;
    vector<Iingredient>* ing;
};

The code above works. But you have to keep in mind that those are normal native C++ pointers and that means you have to manually delete them. To do that property, you should read about how destructors and finalizers work in C++/CLI.