Kne*_*tic 2 c c++ java-native-interface
我知道这是一个相当愚蠢的问题,但没有任何谷歌搜索或代码排列似乎工作.
我有一个像这样定义的结构.
typedef struct
{
int rate;
int duration;
} DummyStructure;
Run Code Online (Sandbox Code Playgroud)
现在,我尝试使用类似于此的代码.
//
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;
Run Code Online (Sandbox Code Playgroud)
我强调我已经尝试了**和*的每一种排列都是可能的.我只是不明白.要么它不编译,要么它没有编译,当它发生时,我最终得到结构2中包含的字段看似随机的数字.我假设不知何故我已经收拾了不正确的内存位置,但除了使用&之外你怎么能得到它?
我有记忆位置,对吗?如何将结构设置到该位置?
编辑; 我忘了提及(后来的答案已经问过),但我打算用这个来为libnibis包装jni.使用jni意味着我无法传回libvorbis所做的任何结构,但它需要它们的核心功能.因此我的包装器将直接使用vorbis来构造结构,并且我将指向它们的指针传递给java,这样当我需要用更多声音填充缓冲区时,我可以简单地从整数值重新引用struct对象指针.
你为什么要尝试将指针转换为整数并返回?只是为了学习,解决问题,解决一些(无限制的)限制,或者是什么?在像这样的"普通"程序中做这件事是一件相当奇怪的事情,因为没有意义.
问题的一个可能原因是,无法保证指针甚至可以适合long int.您可以通过添加以下代码进行检查:
printf("a regular pointer is %u bytes, long int is %u",
(unsigned int) sizeof structure, (unsigned int) sizeof point);
Run Code Online (Sandbox Code Playgroud)
如果打印的数字不同,那可能是导致问题的最大原因.
如果你正在使用C99,你应该#include <stdint.h>然后使用intptr_t类型而不是unsigned long保持指针,无论如何.