Search code examples
c#c++c++-climanaged

Is this possible? Calling managed c++ struct constructor in C#


I've got a managed c++ class/struct with constructors that take input. In C#, I can only "see" the default constructor. Is there a way to call the other constructors, without leaving managed code? Thanks.

Edit: In fact, none of its functions are visible.

C++:

public class Vector4
{
private:
    Vector4_CPP test ;

    Vector4(Vector4_CPP* value)
    {
        this->test = *value;
    }


public:
    Vector4(Vector4* value)
    {
        test = value->test;
    }
public:
    Vector4(float x, float y, float z, float w)
    {
        test = Vector4_CPP( x, y, z, w ) ;
    }


    Vector4 operator *(Vector4 * b)
    {
        Vector4_CPP r = this->test * &(b->test) ;
        return Vector4( &r ) ;
    }
} ;

C#:

// C# tells me it can't find the constructor.
// Also, none of them are visible in intellisense.
Library.Vector4 a = new Library.Vector4(1, 1, 1, 1);

Solution

  • The first problem is that your class declaration is for a unmanaged C++ object.

    If you want a managed C++/CLI object, then you need one of the following:

    public value struct Vector4
    

    or

    public ref class Vector4
    

    Also, any C++/CLI function signature that includes native types will not be visible to C#. So any parameters or return values must be either your C++/CLI managed types or .NET types. I'm not sure how the operator* signature would look, but you could make rest like this:

    public value struct Vector4 
    {   
      private:
        Vector4_CPP test;
    
        Vector4(Vector4_CPP* value)
        {
            this->test = *value;
        }
    
      public:
        Vector4(Vector4 value)
        {
            test = value.test;
        }
    
        Vector4(System::Single x, System::Single y, System::Single z, System::Single w)
        {
            test = Vector4_CPP( x, y, z, w ) ;
        } 
    }
    

    Or:

    public ref class Vector4 
    {   
      private:
        Vector4_CPP test;
    
        Vector4(Vector4_CPP* value)
        {
            this->test = *value;
        }
    
      public:
        Vector4(Vector4^ value)
        {
            test = value->test;
        }
    
        Vector4(System::Single x, System::Single y, System::Single z, System::Single w)
        {
            test = Vector4_CPP( x, y, z, w ) ;
        } 
    }