【问题标题】:Explicit cast operator in Managed C++ for a .NET DLL.NET DLL 的托管 C++ 中的显式转换运算符
【发布时间】:2010-12-10 09:41:49
【问题描述】:

我正在使用托管 C++ (/clr) 为带有 Visual Studio 2008 的本机 DLL 编写一个包装 DLL。 此包装 DLL 将用于 .NET 编程语言,例如 C#。

我对 System::String 的显式强制转换运算符的实现存在问题。 强制转换在托管 C++ 测试程序中有效,但在 C# 测试程序中无效。

这是我在 C# 程序中遇到的错误:

error CS0030: Cannot convert type 'Field' to 'string'

这是我的简化版本:

public ref class Field
{
private:
    FieldNative* nativeObj;

public:
    Field()
    {
        nativeObj = new FieldNative();
    }

    ~Field()
    {        
        delete nativeObj; 
    }

    explicit operator System::String^(void)
    {      
        const char* value = (const char*) *nativeObj;
        return gcnew System::String(value, 0, nativeObj->size());
    }
};

本机对象实现了到 const char* 的转换,所以这是可行的。我什至可以在另一个托管 C++ 程序中使用它。 但是,它不适用于 C#。

这是属性在 VS2008 的对象浏览器中的公开方式:

Field.explicit operator string ()

public explicit operator  string()
Member of Field

我必须如何在托管 C++ 中实现显式转换运算符,以便它可以在 C# 或任何其他 .NET 语言中使用?

【问题讨论】:

    标签: c# .net dll wrapper managed-c++


    【解决方案1】:

    C# 要求运算符是静态的。像这样编写它以使其工作:

        static explicit operator System::String^(Field^ obj)
        {      
            // etc..
        }
    

    【讨论】:

    • @Saeed - 不,它是 C++/CLI,OP 正在使用的语言。
    • 但是你写了C# requires ...所以把c#改成.net,如果是的话。
    猜你喜欢
    • 1970-01-01
    • 2017-02-14
    • 1970-01-01
    • 2012-03-22
    • 2011-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多