C 接收数据
#include <stdio.h>
#include <stdlib.h>
#include <sys/shm.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>
#define SHAERD_MEM_SIZE 20 * 1024 * 1024 // 20MBytes
#define ImgWidth 1024
#define ImgHeight 1024
time_t get_timestamp_ms(void);
int main(int argc, char *argv[])
{
int i,j;
int id = 0;
size_t offset = 0;
char *data = NULL;
unsigned char *ImgData = NULL;
unsigned char *TmpPointer = NULL;
unsigned int file_bytes = 0;
time_t start_time, end_time;
unsigned char ImgDataMatrix[ImgWidth][ImgHeight] = {0};
if (argc < 2)
{
printf("args too less\n");
return 0;
}
id = shmget(123559, SHAERD_MEM_SIZE, IPC_CREAT | 0777);
if (id < 0)
{
printf("get id failed\n");
return 0;
}
data = shmat(id, NULL, 0);
if (data == NULL)
{
printf("shamt failed\n");
return 0;
}
file_bytes =32;
printf("Size of unsigned long:%ld\n", offset);
printf("Size of Image File:%d\n", file_bytes);
start_time = get_timestamp_ms();
memcpy(data, &file_bytes, sizeof(unsigned int));
end_time = get_timestamp_ms();
printf("Time Cost:%ld\n", end_time - start_time);
while(1){
printf("Size of Image File:%d\n", *(unsigned int *)data);
}
return 0;
}
time_t get_timestamp_ms(void)
{
time_t timestamp_ms = 0;
struct timeval tv;
gettimeofday(&tv,NULL);
timestamp_ms = tv.tv_sec * 1000 + tv.tv_usec / 1000;
return timestamp_ms;
}
python
from ctypes import *
#import numpy as np
import codecs
import datetime
SHM_SIZE = 1024*1024*20 # 20MBytes
SHM_KEY = 123559
OUTFILE="Shared.PNG"
try:
rt = CDLL('librt.so')
except:
rt = CDLL('librt.so.1')
shmget = rt.shmget
shmget.argtypes = [c_int, c_size_t, c_int]
shmget.restype = c_int
shmat = rt.shmat
shmat.argtypes = [c_int, POINTER(c_void_p), c_int]
shmat.restype = c_void_p
shmid = shmget(SHM_KEY, SHM_SIZE, 0o666)
# Started by AICoder, pid:e1126e1f06804ae78cd69064c16db868
# 创建一个字符串缓冲区
data = create_string_buffer(b"32")
# Started by AICoder, pid:c7653f15d6fa4372a06674a6a364c981
b_num = bytes(str(64), 'utf-8')
# Ended by AICoder, pid:c7653f15d6fa4372a06674a6a364c981
data = create_string_buffer(b_num)
b_num =c_int(128)
# Ended by AICoder, pid:e1126e1f06804ae78cd69064c16db868
if shmid < 0:
print ("System not infected")
else:
addr = shmat(shmid, None, 0)
#f=open(OUTFILE, 'wb')
begin_time = datetime.datetime.now()
DataLength = int.from_bytes(string_at(addr,4), byteorder='little', signed=True) #这里数据文件是小端int16类型
ImgData = string_at(addr+4,DataLength)
end_time = datetime.datetime.now()
print(DataLength, ' Bytes')
# 计算需要移动的字节数
size = len(data.raw)
size = sizeof(b_num)
# 将数据复制到共享内存地址
#memmove(addr, data, size)
memmove(addr, byref(b_num), size)
#print('Type:',type(ImgData),' Bytes:', len(ImgData))
#f.write(ImgData)
#f.close()
#print ("Dumped %d bytes in %s" % (SHM_SIZE, OUTFILE))
print("Success!",end_time-begin_time)
gcc - o sh share.c
./sh 1
python3 test.py