加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 07:27:32 所属栏目:百科 来源:网络整理
导读:如果我从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/
如果我从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 memoryn",(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在实施中所使用的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读