如何铸就C结构只是另一种结构类型,如果他们的内存大小相等? [英] How to cast C struct just another struct type if their memory size are equal?

查看:84
本文介绍了如何铸就C结构只是另一种结构类型,如果他们的内存大小相等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2矩阵结构是指相等的数据,但有不同的形式这样的:

I have 2 matrix structs means equal data but have different form like these:

// Matrix type 1.
typedef float Scalar;
typedef struct { Scalar e[4]; } Vector;
typedef struct { Vector e[4]; } Matrix;

// Matrix type 2 (you may know this if you're iPhone developer)
// Defines CGFloat as float for simple description.
typedef float CGFloat;
struct CATransform3D
   {
   CGFloat m11, m12, m13, m14;
   CGFloat m21, m22, m23, m24;
   CGFloat m31, m32, m33, m34;
   CGFloat m41, m42, m43, m44;
};
typedef struct CATransform3D CATransform3D;

他们的内存大小是相等的。因此,我相信有一种方法来转换这些类型没有任何指针操作或复制这样的:

Their memory sizes are equal. So I believe there is a way to convert these types without any pointer operations or copy like this:

// Implemented in external lib.
CATransform3D CATransform3DMakeScale (CGFloat sx, CGFloat sy, CGFloat sz);
Matrix m = (Matrix)CATransform3DMakeScale ( 1, 2, 3 );

这可能吗?目前,编译器会打印错误:转换要求的非标型的消息

Is this possible? Currently compiler prints an "error: conversion to non-scalar type requested" message.

推荐答案

也许是最好的解决办法是你的两个结构结合成一个联盟。如果你想跨preT相同的数据在两种不同的方式则是显而易见的选择。另一种方法是使用指针类型转换,但是这是丑陋的,休息重叠规则,并且可以隐藏,否则可能会被编译器报告的错误。

Probably the best solution would be to combine your two structs into a union. If you want to interpret the same data in two different ways then it's the obvious choice. The alternative is to use pointer casts, but that's ugly, breaks aliasing rules, and can hide errors that might otherwise be reported by the compiler.

typedef float Scalar;
typedef struct { Scalar e[4]; } Vector;
typedef struct { Vector e[4]; } Matrix;

struct CATransform3D
{
   CGFloat m11, m12, m13, m14;
   CGFloat m21, m22, m23, m24;
   CGFloat m31, m32, m33, m34;
   CGFloat m41, m42, m43, m44;
};
typedef struct CATransform3D CATransform3D;

typedef union
{
    CATransform3D t;
    Matrix m;
} UMatrix;

CATransform3D CATransform3DMakeScale (CGFloat sx, CGFloat sy, CGFloat sz);
UMatrix um;
um.t = CATransform3DMakeScale ( 1, 2, 3 );
//
// now you can just use um.m when you need to refer to the Matrix type...
//

这篇关于如何铸就C结构只是另一种结构类型,如果他们的内存大小相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆