0

I'm working with an API that gives me a pointer for memory-mapped I/O. It does this by filling in a pointer-to-pointer argument:

int map(void** p);

Because this is memory mapped I/O, I'm pretty sure I should be using volatile here. (I don't know why they didn't make the parameter a volatile void**.)

But, my volatile void** isn't implicitly convertible to the function's void**, so I can't just pass it in directly:

volatile void* p;
map(&p); // Error: no known conversion from 'volatile void **' to 'void **'.

I'm currently working around this with an extra variable and a separate assignment step:

volatile void* p;
void* pNonVolatile;
map(&pNonVolatile);
p = pNonVolatile;

This seems verbose. Is it safe in this case to instead cast the volatile away when passing the pointer in? i.e.

volatile void* p;
map(const_cast<void**>(&p));
Maxpm
  • 24,113
  • 33
  • 111
  • 170
  • 2
    Are you sure it must be volatile? Please, check [this question](https://stackoverflow.com/questions/45753903/memory-mapped-files-and-pointers-to-volatile-objects) – J. Calleja May 27 '18 at 00:04
  • Get a `void *` from the API and then convert it to `volatile void **` if you want. – M.M May 27 '18 at 00:34
  • 1
    Note that `volatile` is neither necessary nor sufficient for inter-process synchronization – M.M May 27 '18 at 00:35
  • You presumably need to cast the return value to some other type to do anything with it, other than pass it back to the same API, anyway? – Davislor May 27 '18 at 01:50

1 Answers1

0

From a C++ language point of view, this could result in undefined behavior in the library, but not in your code using const_cast.

However, from what you have described, the library probably does not use C or C++ to write into this memory space (you mentioned it uses memory-mapped I/O). So the undefined behavior which could exist if the library dereferenced your pointer without volatile is not relevant, because hardware is doing that, not software.

In any case, whether you use const_cast or the "extra pointer then assign" solution doesn't seem to matter. They should be both OK if the memory is written by a hardware device, but not OK if it's written by the library without volatile.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • Can you elaborate on why the extra variable method is potentially just as “not OK” as the cast method? It seems like it’s guaranteed to give the library what it wants and me what I want. – Maxpm May 27 '18 at 01:24
  • In case the library writes to the non-volatile pointer from software, it is not sufficient for you to have a volatile qualified pointer when reading. But in the case where hardware is writing to it, this is implementation dependant and probably well defined for whatever platform you're on. I don't think the cast is better or worse than the extra variable, so you may as well use whichever approach you find more appealing to look at. – John Zwinck May 27 '18 at 12:28