c# - 这可能吗?在 C# 中调用托管 C++ 结构构造函数

标签 c# c++ c++-cli managed

我有一个托管的 C++ 类/结构,其中包含接受输入的构造函数。在 C# 中,我只能“看到”默认构造函数。有没有办法在不离开托管代码的情况下调用其他构造函数?谢谢。

编辑:事实上,它的所有功能都不可见。

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);

最佳答案

第一个问题是您的类声明是针对非托管 C++ 对象的。

如果你想要一个托管的 C++/CLI 对象,那么你需要以下之一:

public value struct Vector4

public ref class Vector4

此外,任何包含 native 类型的 C++/CLI 函数签名对 C# 都是不可见的。因此,任何参数或返回值都必须是您的 C++/CLI 托管类型或 .NET 类型。我不确定 operator* 签名会是什么样子,但你可以这样休息:

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 ) ;
    } 
}

或者:

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 ) ;
    } 
}

关于c# - 这可能吗?在 C# 中调用托管 C++ 结构构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10867225/

相关文章:

c# - MenuItem.IsEnabled 绑定(bind)到是否在列表框中选择了某些内容,但它不会更新

c# - 框架 View 模型

c# - 从 DataTable 填充 ListView

c++ - 如何让编译器使用正确的模板特化?

c++ - 传递多个参数 HttpPostRequest c++

c++ - 将 native 指针转换为托管对象

c++-cli - C++/CLI : How to override Equal method of Object class

reference - C++/CLI 引用未在随后进入本地 block 时初始化为 nullptr

c# - 使用在多个列上具有主键的 Entity Framework 更新数据库

c++ - C++ 中的结构是否类似于枚举或类?