Cad*_*hon 5 c++ python uuid swig random-seed
我的软件是用C++编写的,并由python脚本调用(通过Swig).当在脚本中调用python函数uuid.uuid1()时,C++的std :: rand()使用的种子似乎丢失了.这是一个问题,因为我必须能够在C++代码中以完全相同的行为重新启动我的软件(这不是uniqid的问题).
以下示例简化了该问题:
C++文件testrand.h:
#ifndef __INCLUDE__TESTRAND_H__
#define __INCLUDE__TESTRAND_H__
void initialize(unsigned long int seed);
unsigned long int get_number();
#endif
Run Code Online (Sandbox Code Playgroud)
C++文件testrand.cpp:
#include "testrand.h"
#include <cstdlib>
void initialize(unsigned long int seed)
{
std::srand(seed);
}
unsigned long int get_number()
{
return std::rand();
}
Run Code Online (Sandbox Code Playgroud)
Swig文件testrand.i:
%module testrand
%{
#include "testrand.h"
%}
%include "testrand.h"
Run Code Online (Sandbox Code Playgroud)
使用以下命令完成编译:
swig -python -c++ testrand.i
g++ -c -fPIC testrand.cpp testrand_wrap.cxx -I/usr/include/python2.7/
g++ -shared testrand.o testrand_wrap.o -o _testrand.so
Run Code Online (Sandbox Code Playgroud)
如果我多次启动以下python测试用例,我可以看到第一个数字始终相同(如预期的那样),但是在每次运行时调用uuid.uuid1()后生成的第二个数字会发生变化.
import testrand
import uuid
testrand.initialize(10)
x1 = testrand.get_number()
print x1
uuid.uuid1()
x2 = testrand.get_number()
print x2
Run Code Online (Sandbox Code Playgroud)
几个运行:
> python testcase.py
1215069295
1691632206
> python testcase.py
1215069295
746144017
> python testcase.py
1215069295
377602282
Run Code Online (Sandbox Code Playgroud)
你知道如何在不杀死我的C++种子的情况下使用python uuid吗?提前致谢.(编辑:我的配置:Linux openSUSE 12.3,64位,python 2.7.3(与2.7.2相同的问题),swig 2.0.9,gcc 4.7.2(但与4.5.1相同的问题))
我找到了解决这个问题的方法。实际上,C++ 种子仅由 uuid 模块初始化一次(在函数的第一次调用时uuid.uuid1()
)。如果我通过添加对函数的无用的第一次调用来更改示例脚本,我就不会遇到问题:
import testrand
import uuid
uuid.uuid1()
testrand.initialize(10)
x1 = testrand.get_number()
print x1
uuid.uuid1()
x2 = testrand.get_number()
print x2
Run Code Online (Sandbox Code Playgroud)