[英]How to do placement allocation Eigen::Matrix to Shared Memory (or Heap)?
[英]How to mmap Eigen into shared memory?
我想使用Eigen
庫作為我共享的 memory 數據結構(通過mmap
)。
這是我的代碼:
生產者.cpp:
#include<sys/mman.h>
#include<sys/types.h>
#include<fcntl.h>
#include<string.h>
#include<stdio.h>
#include<unistd.h>
#include <vector>
#include <iostream>
#include <string>
#include "eigen3/Eigen/Dense"
typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> eigen_matrix;
using namespace std;
int main(int argc,char **argv) {
int fd = open(argv[1], O_CREAT | O_RDWR | O_TRUNC, 0777);
size_t size = 100 * 100 * sizeof(typename eigen_matrix::Scalar);
lseek(fd, size, SEEK_SET);
write(fd,"",1);
eigen_matrix* p =(eigen_matrix*)mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
p->resize(100, 100);
(*p)(0, 0) = 1;
double s;
size_t count = 0;
while (std::cin >> s && s != 0) {
(*p)(count++, 0) = s;
}
printf("initialize over\n");
munmap(p, size);
close(fd);
}
消費者.cpp:
#include<sys/mman.h>
#include<sys/types.h>
#include<fcntl.h>
#include<string.h>
#include<stdio.h>
#include<unistd.h>
#include <vector>
#include <iostream>
#include <string>
#include "eigen3/Eigen/Dense"
using namespace std;
typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> eigen_matrix;
int main(int argc,char **argv) {
int fd = open(argv[1], O_RDWR, 0777);
size_t size = 100 * 100 * sizeof(typename eigen_matrix::Scalar);
lseek(fd, size, SEEK_SET);
eigen_matrix* p = (eigen_matrix*)mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0);
close(fd);
printf("%zu %zu\n", p->cols(), p->rows());
cout << *p <<endl; // here crashed !!
std::string s;
while (std::cin >> s && s != "quit") {
cout << *p << endl;
}
munmap(p, size);
}
正如您在代碼中看到的那樣,消費者崩潰了
cout << *p << endl;
你能幫忙嗎? 有什么我忽略的嗎?
動態特征矩陣類似於 std::vector。 它們不保存實際數據,它們包含指向數據的指針和大小信息。 您映射了 object,而不是實際數據。
這樣的事情應該有效:
Eigen::Index rows = 100, cols = 100;
const void* space = mmap(NULL, rows * cols * sizeof(double),
PROT_READ, MAP_SHARED, fd, 0);
Eigen::MatrixXd::ConstMapType mapped = Eigen::MatrixXd::Map(
static_cast<const double*>(space), rows, cols);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.