只写指针类型 [英] Write-Only pointer type
问题描述
我是一个嵌入式系统编写软件。
I'm writing software for an embedded system.
我们正在使用指针访问FPGA器件的寄存器。结果
一些寄存器是只读的,有的则是只写。
We are using pointers to access registers of an FPGA device.
Some of the registers are read-only, while others are write-only.
阅读时,只写寄存器将产生不确定的值。
The write-only registers will produce undefined values when read.
我想定义一个指针类型,使编译器从一个只写寄存器(又名提领)读值时,检测到。
I want to define a pointer type that will allow the compiler to detect when reading values from a write-only registers (a.k.a. dereferencing).
能否只写指针仅使用C语言语法创建的?结果
(我们正在开发使用C第一台样机,但移动在第二代C ++)。
Can a write-only pointer be created using only C language syntax?
(We are developing first prototype using C, but moving to C++ on 2nd generation.)
如何才能有效率只写指针在C ++中创造出来的?
(请记住,这是不是在跟踪动态内存的项目,但访问硬件地址)。
How can an efficient write-only pointer be created in C++? (Remember, this is not tracking items in dynamic memory, but accessing hardware addresses.)
这code使用了嵌入式系统,安全和质量是最高的关注上。
This code is used on an embedded system where safety and quality are highest concerns.
推荐答案
我可能会写每一个微小的包装类:
I'd probably write a tiny wrapper class for each:
template <class T>
class read_only {
T volatile *addr;
public:
read_only(int address) : addr((T *)address) {}
operator T() volatile const { return *addr; }
};
template <class T>
class write_only {
T volatile *addr;
public:
write_only(int address) : addr ((T *)address) {}
// chaining not allowed since it's write only.
void operator=(T const &t) volatile { *addr = t; }
};
至少假设你的系统有一个合理的编译器,我预计这两种被优化,从而生成code是使用原始指针没有区别。用法:
At least assuming your system has a reasonable compiler, I'd expect both of these to be optimized so the generated code was indistinguishable from using a raw pointer. Usage:
read_only<unsigned char> x(0x1234);
write_only<unsigned char> y(0x1235);
y = x + 1; // No problem
x = y; // won't compile
这篇关于只写指针类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!