托管 C++ 中的显式转换运算符对于 .NET DLL
我正在使用 Visual Studio 2008 用托管 C++ (/clr) 为本机 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 语言中使用?
I'm writing a wrapper DLL in Managed C++ (/clr) for a native DLL with Visual Studio 2008.
This wrapper DLL will be used for .NET Programming languages, such as C#.
I have problems with my implementation of an explicit cast operator to System::String.
Casting works in a Managed C++ test program, but not in a C# test program.
This is the error I get in the C# program:
error CS0030: Cannot convert type 'Field' to 'string'
Here's a simplified version of how I've done it:
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());
}
};
The native object implements the casting to const char*, so this works. I can even use it in another managed C++ program.
However, it is not working in C#.
This is how the property is exposed in the Object Browser of VS2008:
Field.explicit operator string ()
public explicit operator string()
Member of Field
How must I implement the explicit cast operator in Managed C++ so it is usable in C# or any other .NET language?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
C# 要求运算符是静态的。像这样写它才能工作:
C# requires operators to be static. Write it like this to make it work: