#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
__declspec(dllexport) char* read_shared_memory() {
char currentPath[MAX_PATH];
DWORD length = GetCurrentDirectoryA(MAX_PATH, currentPath);
if (length == 0 || length > MAX_PATH) {
printf("Error getting current directory.\n");
return NULL;
}
// 构建文件的完整路径
strcat_s(currentPath, MAX_PATH, "\\UDE_temp_data_file.dat");
HANDLE hFile = CreateFileA(currentPath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE) {
printf("Error opening file.\n");
return NULL;
}
DWORD fileSize = GetFileSize(hFile, NULL);
HANDLE hMapFile = CreateFileMappingA(hFile, NULL, PAGE_READWRITE, 0, fileSize, NULL);
if (hMapFile == NULL) {
printf("Error creating file mapping.\n");
CloseHandle(hFile);
return NULL;
}
char* pBuf = (char*)MapViewOfFile(hMapFile, FILE_MAP_WRITE, 0, 0, fileSize);
if (pBuf == NULL) {
printf("Error mapping view of file.\n");
CloseHandle(hMapFile);
CloseHandle(hFile);
return NULL;
}
// 读取数据长度
unsigned int data_length = *(unsigned int*)pBuf;
// 根据数据长度读取实际的数据
char* data = (char*)malloc(data_length + 1); // +1 for null terminator
if (data == NULL) {
printf("Memory allocation failed.\n");
UnmapViewOfFile(pBuf);
CloseHandle(hMapFile);
CloseHandle(hFile);
return NULL;
}
memcpy(data, pBuf + sizeof(unsigned int), data_length);
data[data_length] = '\0'; // null-terminate the string
// 清空文件内容
memset(pBuf,0,fileSize);
// 清理
UnmapViewOfFile(pBuf);
CloseHandle(hMapFile);
CloseHandle(hFile);
return data; // 注意:调用者负责释放这个内存
}
char* read_non_empty_shared_memory() {
char* data = NULL;
while (1) {
data = read_shared_memory();
if (data != NULL && data[0] != '\0') {
break;
}
Sleep(1000); // 每秒尝试一次
}
return data;
}
int main() {
char* data = read_shared_memory();
if (data != NULL) {
printf("Read data: %s\n", data);
free(data); // 释放由read_shared_memory分配的内存
} else {
printf("Failed to read data from shared memory.\n");
}
return 0;
}
window下 使用C语言读取共享内存的数据
于 2024-03-25 18:11:47 首次发布