C++ Interop: How do I call a C# class from native C++, with the twist the class is non-static?

前端 未结 3 1538
北恋
北恋 2020-12-29 01:04

I have a large application written in native C++. I also have a class in C# that I need to call.

If the C# class was static, then it would be trivial (there\'s lots

3条回答
  •  死守一世寂寞
    2020-12-29 01:09

    C++/CLI or COM interop work just as well with non-static classes as with static. Using C++/CLI you just reference your assembly that holds the non-static class and then you can use gcnew to obtain a reference to a new instance.

    What makes you think that this is not possible with your non-static class?

    EDIT: there is example code here.

    using namespace System;
    
    public ref class CSquare
    {
    private:
        double sd;
    
    public:
        CSquare() : sd(0.00) {}
        CSquare(double side) : sd(side) { }
        ~CSquare() { }
    
        property double Side
        {
        double get() { return sd; }
        void set(double s)
        {
            if( s <= 0 )
            sd = 0.00;
            else
            sd = s;
        }
        }
    
        property double Perimeter { double get() { return sd * 4; } }
        property double Area { double get() { return sd * sd; } }
    };
    
    array ^ CreateSquares()
    {
        array ^ sqrs = gcnew array(5);
    
        sqrs[0] = gcnew CSquare;
        sqrs[0]->Side = 5.62;
        sqrs[1] = gcnew CSquare;
        sqrs[1]->Side = 770.448;
        sqrs[2] = gcnew CSquare;
        sqrs[2]->Side = 2442.08;
        sqrs[3] = gcnew CSquare;
        sqrs[3]->Side = 82.304;
        sqrs[4] = gcnew CSquare;
        sqrs[4]->Side = 640.1115;
    
        return sqrs;
    }
    

提交回复
热议问题