开发者

How do I pass a struct from a class to a winform

I tried to do something like this:

        m_mystruct = (Fo开发者_如何学JAVArm1.mystruct)m_myclass.mystruct;

where both structs have same definition.

C# doesn't want to do the cast.

Update: instead of why, I modify my question

How do I pass a struct from a class to a winform ?


Having the "same definition" doesn't make them the same type.

In fact, if there are two definitions, then they are two different types.


Because, while the have the same definition, they are not related in any way.

If you want to be able to cast between the two types, you have to define the explicit/implicit conversions.


If they are defined in two separate places then they are actually two different types.

You could define explicit and implicit operators to convert between the two. It might look like this.

public struct Foo
{
    public int Value;

    public static explicit operator Bar(Foo source)
    {
        var destination = new Bar();
        destination.Value = source.Value;
        return destination;
    }
}

public struct Bar
{
    public int Value;

    public static explicit operator Foo(Bar source)
    {
        var destination = new Foo();
        destination.Value = source.Value;
        return destination;
    }
}

Think about whether you really need two different declarations. But, whatever you decide do not do the following unless you absolutely have no other choice. It could go wrong in so many different ways.

Foo f = new Foo();
IntPtr pf = Marshal.AllocHGlobal(Marshal.SizeOf(f));
Marshal.StructureToPtr(f, pf, false);
Bar b = (Bar)Marshal.PtrToStructure(pf, typeof(Bar));
Marshal.FreeHGlobal(pf);

or

unsafe
{
  Foo f = new Foo();
  Bar b = *(Bar*)&f;
}


They are basically different types!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜