Call C ++ functions from C # /. NET

I have a solution that a C ++ project and a C # project have.

A C ++ project defines the class that I want to create in C # and call its member functions. So far I have managed to create an instance of the class:

CFoo Bar = new CFoo();

But when I try to call a function on it, the compiler says that it is not available.

Also, when I inspect an object in the debugger, the elements are not displayed.

What am I missing here?

+3
source share
1 answer

You need to declare the class in C ++ / CLI as ref class.

(Note that we are talking about C ++ / CLI, not C ++. I assume that you must include the CLR in your C ++ project or you cannot get the new one CFooto work.)

Edit:

ref.

, ++:

class FooUnmanaged
{
    int x;

    FooUnmanaged() : x(5) {}
};

CLR:

ref class FooManaged
{
    FooUnmanaged m;
};

, , . :

ref class FooManaged
{
    FooUnmanaged *m;
};

. , , , System.IntPtr .

, , delete. :

ref class FooManaged
{
    FooUnmanaged *u;

public:
    FooManaged(FooUnmanaged *u_)
        : u(u_) { }

    ~FooManaged() { delete u; }
};

, ++. , ++/CLI .

, IL , FooManaged IDisposable, Dispose. .NET- , . #

using (var m = new FooManaged())
{

    // end of block: m will be disposed (and so FooUnmanaged will be deleted)
}
+7

Source: https://habr.com/ru/post/1713328/


All Articles