使用共享内存从单独的 C 进程访问 numpy 数组

MRo*_*lin 5 c python numpy shared-memory

我内存中有一个一维 numpy 数组

>>> x = np.arange(5)
Run Code Online (Sandbox Code Playgroud)

我想使用共享内存与同一台计算机上的单独且独立(非分叉)的 C 进程共享此数据。

我期望做类似以下的事情:

  1. 从 Python 中分配新的共享内存块
  2. 将当前数据复制到该块中
  3. 获取数组的数据类型、长度和全局地址,并将它们传递给 C 进程(现在,我们将通过命令行界面传递给 C 进程)
  4. 在 C 中创建一个指向内存地址的适当类型的指针
  5. 用 C 做一些简单的计算

实现这些步骤的最佳方法是什么?似乎有几种 Python 解决方案可以在共享内存中分配数组数据。我能找到的所有示例都涉及两个 Python 进程之间的共享,而不是 Python 和另一种语言之间的共享。

非常欢迎最小的例子。

MRo*_*lin 4

这是一个最小的例子:

Python

import os

import posix_ipc
import numpy as np

x = np.arange(1000, dtype='i4')
f = posix_ipc.SharedMemory('test', flags=posix_ipc.O_CREAT, size=x.nbytes, read_only=False)

ff = os.fdopen(f.fd, mode='wb')
ff.write(x.data)
ff.close()  # flush doesn't work, but this does.
Run Code Online (Sandbox Code Playgroud)

C

// shm.c
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/mman.h>

int main(int argc, char *argv[])
{
    int i, fd;
    int *data;

    fd = shm_open("test", O_RDONLY, 0);
    if (fd == -1)
        printf("Error!, bad file desciptor");

    data = mmap(NULL, sizeof(int), PROT_READ, MAP_PRIVATE, fd, 0);
    if (data == MAP_FAILED)
        printf("Error!, map failed!");

    for(i = 0; i < 1000; i++){
        printf("%d, ", (int)data[i]);
    }
    return 0;
}

$ gcc shm.c -lrt -o shm
$ ./shm 
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, ...
Run Code Online (Sandbox Code Playgroud)