简体   繁体   English

C 铸造结构的返回值

[英]C casting return values of structures

On an old C compiler that only passes structures by pointers I fortunately have a structure that is 4 bytes long.在仅通过指针传递结构的旧 C 编译器上,幸运的是我有一个 4 字节长的结构。 Which is the size of a long (not int) on this system.这是该系统上 long(不是 int)的大小。

The code I'm porting (awk V7 or 32V) has many functions that return this structure by value.我正在移植的代码(awk V7 或 32V)具有许多按值返回此结构的函数。

I'm trying to find a way to cast the structure a long and visa versa and while I have managed this for variables the cast fails with the return value of a function.我试图找到一种方法来长期转换结构,反之亦然,虽然我已经为变量管理了这个,但转换失败,返回值为 function。 I would be forced to use a temp long and then cast that.我将被迫使用临时长,然后施放。 This means more than a simple define to solve my issue and means avoidable recoding.这不仅仅意味着解决我的问题的简单定义,还意味着可避免的重新编码。

Is there a way I can do this with just defines?有没有办法只用定义来做到这一点?

I have some sample code here that I'm playing around with.我在这里有一些示例代码,我正在玩弄。 Sample code from different system has long of 64 bits so using int32 as long.来自不同系统的示例代码长度为 64 位,因此使用 int32 一样长。

#include <stdio.h>

typedef struct _obj { char a; char b; short c; } Obj;

#define OBJ2INT *(int32*)&
#define INT2OBJ *(Obj*)&

/* Obj */ int32 newObj(a, b, c) /* was returing Obj */
char a; char b; int c;
{
    Obj newobj;
    newobj.a = a;
    newobj.b = b;
    newobj.c = c;
    return OBJ2INT newobj;
}

int main(argc, argv)
int argc; char *argv[];
{
    Obj a, b;
    int32 t;

    t = newObj('a', '1', 1));
    a = INT2OBJ t; /* this works but require recoding with a temp variable */
    b = INT2OBJ newObj('b', '2', 2); /* this is not allowed. even though the value is on the stack there is no address for return value */

    printf("a = %c %c %d\n", a.a, a.b, a.c);
    printf("b = %c %c %d\n", b.a, b.b, b.c);
}

I was missing the whole point.我错过了重点。 K & R C cannot assign or pass structures/unions. K & R C 不能分配或传递结构/联合。

So converting the int32 to a structure and assigning to another structure is never going to work.因此,将 int32 转换为结构并分配给另一个结构永远不会起作用。 Can't assign structures.无法分配结构。 So the structure must always be converted to an int32.因此,必须始终将结构转换为 int32。 because int32 can be assigned and passed: The solution was to change this :因为 int32 可以被分配和传递:解决方案是改变这个:

b = INT2OBJ newObj('b', '2', 2); /* this is not allowed. even though the value is on the stack there is no address for return value */

to this:对此:

   OBJ2INT b = newObj('b', '2', 2);

INT2OBJ is never required.从来不需要 INT2OBJ。 What was required was moving the INT2OBJ from the right to a OBJ2INT on the left of the assignment!需要将 INT2OBJ 从右侧移动到作业左侧的 OBJ2INT!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM