How to idiomatically convert `` char * `` to `` double * ``

I retrain C ++ and I am trying to work with boost::iostreams::mapped_file. This class maps the file data to char*, I would like to pass it to double*(since I work with doubling).

I could use it with C-style cast:, double* foo = (double*) databut I'm trying to use idiomatic C ++, and C ++ prefers C ++: static_castetc.

I figured it out:

double* data = static_cast<double*>((void*)file.data());

(file-> data returns char*). This is actually not cleaner.

Here is what I am trying to do (this code works!):

BOOST_AUTO_TEST_CASE(OpenMMapArray){

typedef boost::multi_array_ref<double, 3> arrayd3;
typedef std::array<size_t, 3> index3d;

index3d shape = {{ 20, 20, 20 }};

size_t size = sizeof(double)*std::accumulate(shape.begin(), shape.end(), 1, std::multiplies<size_t>());

boost::iostreams::mapped_file file;

boost::iostreams::mapped_file_params params;

params.path = "/tmp/mmaptest-2";
params.mode = std::ios::in | std::ios::out;
params.new_file_size =  size;

file.open(params);

double* data = static_cast<double*>((void*)file.data());

arrayd3 array(data, shape);

array[0][0][0] = 20;
array[0][1][0] = 19;
array[1][0][0] = 18;
array[0][0][5] = 17;

BOOST_CHECK(data[0] == 20);
BOOST_CHECK(data[20] == 19);
BOOST_CHECK(data[20*20] == 18);
BOOST_CHECK(data[5] == 17);

file.close();
}
+3
source share
1 answer

In this particular case, you are actually trying to re-interpret the data as a different type. Thus, it reinterpret_casthas the order:

double* data = reinterpret_cast<double*>(file.data());
+6
source

All Articles