c++ - 访问私人课程
问题描述
我正在编写一个为 C++ 代码生成 C(技术上是 C 的超集)包装器的程序。如果输入是这样的:
class c {
class priv{};
public:
typedef priv mytypedef; // Provides a way to construct priv
static priv myfactory() {priv ret; return ret;} // Provides another way to construct priv
};
生成的包装器如下所示:
template <typename T>
auto destruct_or_throw(T* t) -> decltype(t->~T()) {
t->~T();
}
auto destruct_or_throw(void*) -> void {
std::abort();
}
void *c_mytypedef_wrapper() {
auto ptr = (c::mytypedef *)malloc(123); // In my usecase, I know the size of the priv class
c::mytypedef val;
*ptr = val;
return ptr;
}
void *c_myfactory_wrapper() {
auto ptr = (decltype(c::myfactory()) *) malloc(123); // In my usecase, I know the size of the priv class
auto val = c::myfactory();
*ptr = val;
return ptr;
}
void c_callable_destruct(void* t) {
// destruct_or_throw((c::priv *) t); // compile error, because priv is private
destruct_or_throw((decltype(c::myfactory()) *) t); // would work, but relies on us having the string "myfactory" when codegenerating this
destruct_or_throw((c::mytypedef *) t); // would work, but relies on us having the string "mytypedef" when codegenerating this
free(t);
}
int main() { // example use
auto val1 = c_mytypedef_wrapper();
c_callable_destruct(val1);
auto val2 = c_myfactory_wrapper();
c_callable_destruct(val2);
}
困难的部分是破坏c_callable_destruct
. 如果代码生成包装器的程序具有字符串“mytypedef”或“myfactory”,那么我可以使用
destruct_or_throw((decltype(c::myfactory()) *) t);
或者
destruct_or_throw((c::mytypedef *) t);
破坏它。如果priv
不是私人的,那么我可以使用
destruct_or_throw((c::priv *) t);
破坏它。不幸的是,priv 是私有的,当我的程序代码生成时c_callable_destruct
,没有简单的方法来获取字符串“mytypedef”或“myfactory”。知道如何破坏这个对象吗?
编辑:我的旧问题措辞不佳:这是旧的措辞:
假设我有一个私人声明的类priv
:
class c {
class priv{};
};
这意味着下面的代码
void priv_arg(c::priv* ptr) {...}
不会编译。是否可以编译下面的代码?我需要编写一个函数,该函数将指向 ac::priv (或具有相同布局的任何其他类型)的指针作为参数,并且我无法触及c
该类。
我知道您可以访问私有成员变量(https://github.com/martong/access_private),但我不知道如何访问私有类型。
解决方案
推荐阅读
- php - PHP Css数组将每个值与最后的单位分开
- ffmpeg - 如何以无损的最佳质量从 H265 4K 视频中导出 FFmpeg 帧?
- python - Spark 安装问题 -TypeError: an integer is required (got type bytes) - spark-2.4.5-bin-hadoop2.7, hadoop 2.7.1, python 3.8.2
- c++ - 我在不使用 STL 的情况下反转向量时遇到分段错误
- powershell - 尝试使用 Powershell 在 AD 中查找启用或禁用的用户
- string - 在火花数据框中如何使用scala将字符串类型的日期列转换为日期类型的日期列
- python - 编写“python manage.py makemigrations”时出现一条很长的错误消息,说明语法无效
- sql-server - 导入到文本文件 sql 时,选择的列显示 2 行
- python - 在 python 中检查列表项是否为 mo/dd/yy 格式?
- python - 硒的自定义命令循环?