我在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++中全局变量的初始化顺序没有控制。但也许还有别的方法可以让我做得更好?你知道吗
Hello.py
,以防止用户简单地删除对LicenseManager的调用。但是它的安全性很差,因为Python很容易反编译。你知道吗
回答我自己的问题。你知道吗
<>实际上,在初始化库时,可以用SWIG添加C++代码。然后我只需在Swig文件中添加以下代码:相关问题 更多 >
编程相关推荐