Miguel
Miguel

Reputation: 3506

Some questions about C++/CLI and C# integration

Good night,

I was trying to make a simple dll in C++/CLI to use in my c# library using something like the following code:

// This is the main DLL file.

#include "stdafx.h"

namespace Something
{
    public class Tools
    {
        public : int Test (...)
        {
            (...)
        }
    }
}

I can compile the dll and load it into the C# project without any problems, and can use the namespace Something and the class Tools from C#. The problem is that when I try to write Tools.Test(something) I get an error message saying that Tools doesn't have a definition for Test. Why can't the compiler get the function, even if it is declared public?

Also... Can I share a class across two project, half written in C# and half written in managed C++?

Thank you very much.

Upvotes: 0

Views: 503

Answers (3)

shf301
shf301

Reputation: 31404

You can share a managed class across a project, but what you've written in an unmanaged (i.e. standard C++ class. Use the ref class keyword to define a managed class in C++.

// This is the main DLL file.

#include "stdafx.h"

namespace Something
{
    public ref class Tools
    {
        public : int Test (...)
        {
            (...)
        }
    }
}

Upvotes: 1

Colin Thomsen
Colin Thomsen

Reputation: 1806

C# can only access managed C++ classes. You would need to use public ref class Tools to indicate that Tools is a managed class to make it accessible from C#. For more info see msdn.

This class can then be used in either managed C++ or C#. Note that managed C++ classes can also use native C++ classes internally.

Upvotes: 1

Preet Sangha
Preet Sangha

Reputation: 65556

The function is not static. try this in the

var someTools = new Tools();
int result = someTools.Test(...);

or make the method static :

public : 
   static int Test (...)
   {
            (...)
   }

Upvotes: 0

Related Questions