库中的全局变量在使用时尚未初始化

2024-09-26 22:07:34 发布

您现在位置:Python中文网/ 问答频道 /正文

上下文:

我在C++中为Python创建了一个模块(我称之为hello)。C++和Python之间的接口是用Sigg制作的。它生成一个动态库_Hello.so和一个Python文件Hello.py。当它被创造出来的时候,我只能这样称呼它:

python
>>> import Hello
>>> Hello.say_hello()
Hello World !
>>>

我想用许可证保护这个模块,然后我想在导入模块时加载许可证。你知道吗

我的实现:

为了确保在导入模块时加载了许可证,我创建了一个单例实例来实例化一个全局变量:

文件LicenseManager.hpp

class LicenseManager
{
  private:
    static LicenseManager licenseManager; // singleton instance
  public:
    static LicenseManager& get(); // get the singleton instance

  public:
    LicenseManager();  // load the license
    ~LicenseManager();  // release the license
  private:
    LicenseManager(const LicenseManager&);  // forbidden (singleton)
    LicenseManager& operator = (const LicenseManager&); // forbidden (singleton)
};

文件LicenseManager.cpp

LicenseManager LicenseManager::licenseManager;  // singleton instance

LicenseManager& LicenseManager::get()
{
  return LicenseManager::licenseManager;
}

LicenseManager::LicenseManager()
{
  /*
   * Here is the code to check the license
   */
  if(lic_ok)
    std::cout << "[INFO] License found. Enjoy this tool !" << std::endl;
  else
  {
    std::cerr << "[ERROR] License not found..." << std::endl;
    throw std::runtime_error("no available licenses");
  }
}

LicenseManager::~LicenseManager()
{}

这个很好用!当我加载模块时,我得到:

python
>>> import Hello
[INFO] License found. Enjoy this tool !
>>> Hello.say_hello()
Hello World !
>>>

我的问题:

实际上,在我的构造函数中检查许可证的代码使用库Crypto++。我有一个来自这个库的分段错误,但是主函数中的相同代码工作得很好。然后我认为Crpyto++也使用全局变量,当调用LicenseManager的构造函数时,这些变量还没有初始化。你知道吗

我知道C++中全局变量的初始化顺序没有控制。但也许还有别的方法可以让我做得更好?你知道吗

糟糕的解决方案:

  • 如果singleton未初始化为全局变量,则在导入时模块不受保护。一个解决方案是在模块的每个功能性中添加一个检查,并强制用户在使用之前调用LicenseManager。这对我来说不是一个解决方案,因为我不能重写所有的模块来强加它(这个模块实际上非常庞大)。你知道吗
  • 在Swig配置文件中,我可以添加加载模块时调用的Python代码。然后我必须编译Hello.py,以防止用户简单地删除对LicenseManager的调用。但是它的安全性很差,因为Python很容易反编译。你知道吗

Tags: 模块文件theinstancehellogetlicensestd
1条回答
网友
1楼 · 发布于 2024-09-26 22:07:34

回答我自己的问题。你知道吗

<>实际上,在初始化库时,可以用SWIG添加C++代码。然后我只需在Swig文件中添加以下代码:

%init%{
  LicenseManager::get();
%}

相关问题 更多 >

    热门问题