【问题标题】:Dealing with Class Ambiguity without changing the library code在不更改库代码的情况下处理类歧义
【发布时间】:2021-03-01 16:52:36
【问题描述】:

我有一个链接两个共享库的 C++ 代码(比如说 foo1.so 和 foo2.so)。在这两个库中,我都有一个名为“Mesh”的类,当我尝试实例化类 Mesh 时,编译器无法知道我正在尝试使用哪一个(显然我知道我想实例化哪一个)。我收到“错误:对‘Mesh’的引用不明确”

当然,我可以更改其中一个库的源代码,将 Mesh 类包装在命名空间周围,这样就可以解决问题。不过,我想避免更改库的代码。有没有办法消除使用库的源文件中的这种歧义?

谢谢你, 拉斐尔。

【问题讨论】:

  • 抱歉,答案是否定的。除了使用命名空间之外,您无法区分。这就是为什么每个库命名空间被认为是一件好事。
  • 这些是动态库还是静态库? This answer 提到创建 2 个动态链接库 - 每个库都静态链接到冲突库之一。
  • 如果您使用动态库,则可以动态加载每个库(参见dl),然后使用句柄来区分调用。

标签: c++ namespaces


【解决方案1】:

通过使用动态库(Linux 中的.so),您可以加载每个库并使用每个句柄来区分调用。 见Dynamically Loaded (DL) Libraries

例如:

#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>

class Meshib
{
    void * _handle;
    double (*_cosine)(double);

public:
    Meshib( const char * libraryPath)
    {
        char *error;

        _handle = dlopen (libraryPath, RTLD_LAZY);
        if (!_handle) {
            fputs (dlerror(), stderr);
            exit(1);
        }
        
        _cosine = reinterpret_cast<decltype(_cosine)>( dlsym(_handle, "cosine") );
        if ((error = dlerror()) != NULL)  {
            fputs(error, stderr);
            exit(1);
        }
    }

    ~Meshib() {
        dlclose(_handle);
    }

    double cosine(double v) { return (*_cosine)(v); }
};



int main(int argc, char **argv)
{
    Meshib meshLib1( "foo1.so" );
    Meshib meshLib2( "foo2.so" );

    printf("%f\n", meshLib1.cosine(2.0));
    printf("%f\n", meshLib2.cosine(2.0));
}

有关 C++ 类动态加载,请参阅 this article

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 2017-11-20
    • 2011-09-07
    • 2012-06-08
    • 1970-01-01
    • 2018-03-18
    • 1970-01-01
    相关资源
    最近更新 更多