有点,有点共享内存。所以不完全是 OP 想要的。
这适用于内存映射文件。我不以任何方式声称高速或高效。这些只是为了展示它的工作示例。
$ python --version
Python 3.7.9
$ g++ --version
g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
C++ 端只监控它需要的值。 Python 端只提供值。
注意:文件名“pods.txt”在C++和python代码中必须一致。
#include <sys/mman.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(void)
{
// assume file exists
int fd = -1;
if ((fd = open("pods.txt", O_RDWR, 0)) == -1)
{
printf("unable to open pods.txt\n");
return 0;
}
// open the file in shared memory
char* shared = (char*) mmap(NULL, 8, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
// periodically read the file contents
while (true)
{
printf("0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X\n", shared[0], shared[1], shared[2], shared[3], shared[4], shared[5], shared[6], shared[7]);
sleep(1);
}
return 0;
}
python方面:
import mmap
import os
import time
fname = './pods.txt'
if not os.path.isfile(fname):
# create initial file
with open(fname, "w+b") as fd:
fd.write(b'\x01\x00\x00\x00\x00\x00\x00\x00')
# at this point, file exists, so memory map it
with open(fname, "r+b") as fd:
mm = mmap.mmap(fd.fileno(), 8, access=mmap.ACCESS_WRITE, offset=0)
# set one of the pods to true (== 0x01) all the rest to false
posn = 0
while True:
print(f'writing posn:{posn}')
# reset to the start of the file
mm.seek(0)
# write the true/false values, only one is true
for count in range(8):
curr = b'\x01' if count == posn else b'\x00'
mm.write(curr)
# admire the view
time.sleep(2)
# set up for the next position in the next loop
posn = (posn + 1) % 8
mm.close()
fd.close()
要在终端 #1 中运行它:
a.out # or whatever you called the C++ executable
0x00 0x00 0x00 0x00 0x01 0x00 0x00 0x00
0x00 0x00 0x00 0x00 0x01 0x00 0x00 0x00
0x01 0x00 0x00 0x00 0x00 0x00 0x00 0x00
0x01 0x00 0x00 0x00 0x00 0x00 0x00 0x00
0x00 0x01 0x00 0x00 0x00 0x00 0x00 0x00
0x00 0x01 0x00 0x00 0x00 0x00 0x00 0x00
0x00 0x00 0x01 0x00 0x00 0x00 0x00 0x00
0x00 0x00 0x01 0x00 0x00 0x00 0x00 0x00
0x00 0x00 0x00 0x01 0x00 0x00 0x00 0x00
即由于 C++ 代码中的 sleep(2),您应该会看到 0x01 每隔几秒移动一步。
在 2 号航站楼:
python my.py # or whatever you called the python file
writing posn:0
writing posn:1
writing posn:2
即您应该会看到位置从 0 到 7 再次变回 0。