C++ 如何在VisualStudio中隐藏静态库中的类

C++ 如何在VisualStudio中隐藏静态库中的类,c++,c,visual-studio,static-libraries,C++,C,Visual Studio,Static Libraries,我只想有2个外部C函数,它们是如何与API交互的。然后在static.lib中,我想让我的类完成所有的工作。但是它不应该被外界看到 通过在编译单元中声明纯C函数是静态的,我可以用纯C函数实现,但是如何用类实现呢?也许您可以用C函数镜像类的API,有点像这样: class Cpp { int i = 0; public: int get_i() { return i; } void set_i(int i) { this->i = i; } }; // C co

我只想有2个外部C函数,它们是如何与API交互的。然后在static.lib中,我想让我的类完成所有的工作。但是它不应该被外界看到


通过在编译单元中声明纯C函数是静态的,我可以用纯C函数实现,但是如何用类实现呢?

也许您可以用C函数镜像类的API,有点像这样:

class Cpp
{
    int i = 0;

public:

    int get_i() { return i; }
    void set_i(int i) { this->i = i; }
};

// C code has a void* as a handle to access
// the correct instance of CPP
extern "C" void* new_Cpp()
{
    return new Cpp;
}

extern "C" void delete_Cpp(void* cpp)
{
    delete reinterpret_cast<Cpp*>(cpp);
}

extern "C" int Cpp_get_i(void* cpp)
{
    return reinterpret_cast<Cpp*>(cpp)->get_i();
}

extern "C" void Cpp_set_i(void* cpp, int i)
{
    return reinterpret_cast<Cpp*>(cpp)->set_i(i);
}
类Cpp
{
int i=0;
公众:
int get_i(){return i;}
无效集_i(int i){this->i=i;}
};
//C代码有一个void*作为访问句柄
//CPP的正确实例
外部“C”无效*新的_Cpp()
{
返回新的Cpp;
}
外部“C”无效删除\u Cpp(无效*Cpp)
{
删除重新解释(cpp);
}
外部“C”int Cpp_get_i(无效*Cpp)
{
return reinterpret_cast(cpp)->get_i();
}
外部“C”无效Cpp_集_i(无效*Cpp,内部i)
{
返回重新解释投射(cpp)->设置投射i(i);
}

如果我很理解你的问题:

  • 您希望创建一个静态库,只向外界显示两个函数
  • 但是这个库的内部应该基于一个你想对外界隐藏的类
  • 您知道如何在经典c中隐藏内部(即使用辅助静态函数和静态变量),但看不到如何处理类
如果是这种情况,诀窍就是简单地使用未命名的名称空间

在您的库源中,您将有如下内容:

namespace {  // anonymous
    class U {   // class visible only to the library
    public: 
        int y;  
        U() :y(0) { cout << "U\n"; } 
        void mrun() { y++; } 
    };
}

void f() {
    U x; 
    ...
}
即使辅助类将在外部世界声明:

class U { public: int y;  U(); void mrun(); };
如果试图使用U,它将无法使用,并且会生成链接错误。这是因为未命名的命名空间对于每个编译单元都是唯一的


如果使用同一种解决方案,但没有匿名名称空间,则辅助类将可见,链接将成功

除非他们有确切的类定义,否则他们就无能为力。可能不值得花时间去担心。
class U { public: int y;  U(); void mrun(); };