微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – 在OSX上从x86读取共享内存到x64,反之亦然

如果我从64位应用程序创建一个SM并在32位应用程序上打开它失败.

//for 64 bit
    shared_memory_object( create_only,"test",read_write) ; 
// for 32 bit
    shared_memory_object (open_only,read_write);

由64位应用程序创建的文件位于以下路径:

/private/tmp/boost_interprocess/AD21A54E000000000000000000000000/test

由32位应用程序搜索文件在路径中

/private/tmp/boost_interprocess/AD21A54E00000000/test

因此32位应用程序无法读取该文件.

我在Mac OS X上使用boost 1.47.0.
这是一个错误吗?我是否必须进行一些设置才能使用某些宏来修复它?有没有人遇到过这个问题?

解决方法

共享内存是否由文件支持是否重要?如果没有,您可以考虑使用底层的Unix共享内存API:shmget,shmat,shmdt和shmctl,所有这些都在sys / shm.h中声明.我发现它们非常容易使用.

// create some shared memory
int id = shmget(0x12345678,1024 * 1024,IPC_CREAT | 0666);

if (id >= 0)
{
    void* p = shmat(id,0);

    if (p != (void*)-1)
    {
        initialize_shared_memory(p);

        // detach from the shared memory when we are done;
        // it will still exist,waiting for another process to access it
        shmdt(p);
    }
    else
    {
        handle_error();
    }
}
else
{
    handle_error();
}

一个进程将使用这样的东西来访问共享内存:

// access the shared memory
int id = shmget(0x12345678,0);

if (id >= 0)
{
    // find out how big it is
    struct shmid_ds info = { { 0 } };

    if (shmctl(id,IPC_STAT,&info) == 0)
        printf("%d bytes of shared memory\n",(int)info.shm_segsz);
    else
        handle_error();

    // get its address
    void* p = shmat(id,0);

    if (p != (void*)-1)
    {
        do_something(p);

        // detach from the shared memory; it still exists,but we can't get to it
        shmdt(p);
    }
    else
    {
        handle_error();
    }
}
else
{
    handle_error();
}

然后,当使用共享内存完成所有进程时,使用shmctl(id,IPC_RMID,0)将其释放回系统.

您可以使用命令行上的ipcs和ipcrm工具来管理共享内存.在首次编写共享内存代码时,它们可用于清除错误.

总而言之,我不确定在32位和64位程序之间共享内存.我建议尝试Unix API,如果它们失败,可能无法完成.毕竟,它们是Boost在实施中所使用的.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐