首页 > 解决方案 > 访问私人课程

问题描述

我正在编写一个为 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),但我不知道如何访问私有类型。

标签: c++private

解决方案


推荐阅读