【发布时间】:2011-12-12 08:15:12
【问题描述】:
我知道这是一个相当愚蠢的问题,但似乎没有多少谷歌搜索或代码排列有效。
我有一个这样定义的结构。
typedef struct
{
int rate;
int duration;
} DummyStructure;
现在,我尝试使用类似的代码。
//
DummyStructure* structure;
DummyStructure* structure2;
long int point;
//
structure = (DummyStructure*)malloc(sizeof(DummyStructure));
structure->rate = 19;
structure->duration = 92;
point = (long int)&structure;
// now i'd like to set structure2 to the same memory location as 1.
// point is the 8-byte int location (i assume?) of structure.
// so naturally i'd assume that by casting as a DummyStructure pointer
// that long int would act as a pointer to that 1.
// It doesn't.
structure2 = (DummyStructure*)point;
我强调我已经尝试了所有可能的 ** 和 * 排列。我只是不明白。它要么不编译,要么编译,当它编译时,我最终得到结构2中包含的字段的看似随机的数字。我假设我以某种方式结束了一个不正确的内存位置,但是除了使用 & 之外,你还能如何获得它?
我有记忆位置,对吧?如何将结构设置到该位置?
编辑;我忘了提(以及随后的答案),但我打算用它来为 jni 包装 libvorbis。使用 jni 意味着我不能回传 libvorbis 所做的任何结构,但它的核心功能需要它们。因此,我的包装器将直接使用 vorbis 来制作结构,并将指向它们的指针传递回 java,这样当我需要用更多声音填充缓冲区时,我可以简单地从整数值重新引用结构对象指针。
【问题讨论】:
-
请注意,您不应该从
malloc(3)转换返回值——只需#include <stdlib.h>,您将获得malloc(3)原型,它允许编译器为您处理所有事情。这些转换可以隐藏编译器警告消息,提醒您代码中的错误。 -
很可能
long不够长,无法保存指针值。使用(u)intptr_t、size_t或long long可能会获得更好的结果。 -
出于好奇,你为什么要使用 long int 呢?
-
Alex,不应该涉及运气,因为
DummyStructure**工作正常。 -
@KeithIrwin:由于这个问题被标记为
jni,我猜他想将指针转换为可以作为句柄传递给Java应用程序的类型。
标签: c++ c java-native-interface