有一个任务是调用一个dll里面的函数,这个函数需要使用malloc来分配大量堆内存但是目前的问题是有很多进程调用这个dll,由于进程间堆是私有的,导致了每个进程都要去分配内存造成内存占用太大,所以想把这个dll改成com组件来解决这个问题,不知道com组件用malloc分配的内存对所有调用的进程都是共享的吗?如果是,这个内存是不是最先调用该com组件的进程分配的?谢谢.

解决方案 »

  1.   

    malloc分配的都是在进程的堆里。如果想跨进程共享数据,COM用IMalloc接口来分配内存。这样分配的内存可以在另外一个进程内释放。
      

  2.   

    不是所有进程都共享的,用malloc之类的话是每个进程私有的.
    你可以使用内存文件映射.来共享内存.这样所有实例使用的是同一段内存.
    CreateFileMapping MapViewOfFileEx
      

  3.   

    我用IMalloc不行 一个进程分配了之后另一个进程去读不出来不知道进程外com组件行不行得通?
      

  4.   

    CoGetMalloc(MEMCTX_SHARED .... 用这个参数。MEMCTX_SHARED returns an optionally-provided shared allocator; if the shared
    allocator is not supported, E_INVALIDARG is returned. When supported, the
    shared allocator returned by this function is an COM-provided implementation
    of IMalloc interface, one which allocates memory in such a way that it can be
    accessed by other process on the current machine simply by conveying the
    pointer to said applications.2. Further, memory allocated by this shared
    allocator in one application may be freed by the shared allocator in another.
    Except when a NULL pointer is passed, the shared memory allocator never
    answers -1 to IMalloc::DidAlloc; it always indicates that either did or did not
    allocate the passed pointer.
      

  5.   

    “CreateFileMapping、MapViewOfFileEx”是唯一可行的解法!只不过速度慢点。而且多个进程共享,你还要做好同步,比如使用Mutex之类。另外CoGetMalloc(MEMCTX_SHARED是在扯淡了,不要信。至少微软是没有公开承认的。