本文整理汇总了C++中py::Dict::ptr方法的典型用法代码示例。如果您正苦于以下问题:C++ Dict::ptr方法的具体用法?C++ Dict::ptr怎么用?C++ Dict::ptr使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类py::Dict
的用法示例。
在下文中一共展示了Dict::ptr方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: setTools
void TooltablePy::setTools(Py::Dict arg)
{
getTooltablePtr()->Tools.clear();
PyObject* dict_copy = PyDict_Copy(arg.ptr());
PyObject *key, *value;
Py_ssize_t pos = 0;
while (PyDict_Next(dict_copy, &pos, &key, &value)) {
if ( PyObject_TypeCheck(key,&(PyInt_Type)) && (PyObject_TypeCheck(value,&(Path::ToolPy::Type))) ) {
int ckey = (int)PyInt_AsLong(key);
Path::Tool &tool = *static_cast<Path::ToolPy*>(value)->getToolPtr();
getTooltablePtr()->setTool(tool,ckey);
} else {
throw Py::Exception("The dictionary can only contain int:tool pairs");
}
}
}
示例2: projectToSVG
Py::Object projectToSVG(const Py::Tuple& args, const Py::Dict& keys)
{
static char* argNames[] = {"topoShape", "direction", "type", "tolerance", "vStyle", "v0Style", "v1Style", "hStyle", "h0Style", "h1Style", NULL};
PyObject *pcObjShape = 0;
PyObject *pcObjDir = 0;
const char *extractionTypePy = 0;
ProjectionAlgos::ExtractionType extractionType = ProjectionAlgos::Plain;
const float tol = 0.1f;
PyObject* vStylePy = 0;
ProjectionAlgos::XmlAttributes vStyle;
PyObject* v0StylePy = 0;
ProjectionAlgos::XmlAttributes v0Style;
PyObject* v1StylePy = 0;
ProjectionAlgos::XmlAttributes v1Style;
PyObject* hStylePy = 0;
ProjectionAlgos::XmlAttributes hStyle;
PyObject* h0StylePy = 0;
ProjectionAlgos::XmlAttributes h0Style;
PyObject* h1StylePy = 0;
ProjectionAlgos::XmlAttributes h1Style;
// Get the arguments
if (!PyArg_ParseTupleAndKeywords(
args.ptr(), keys.ptr(),
"O!|O!sfOOOOOO",
argNames,
&(TopoShapePy::Type), &pcObjShape,
&(Base::VectorPy::Type), &pcObjDir,
&extractionTypePy, &tol,
&vStylePy, &v0StylePy, &v1StylePy,
&hStylePy, &h0StylePy, &h1StylePy))
throw Py::Exception();
// Convert all arguments into the right format
TopoShapePy* pShape = static_cast<TopoShapePy*>(pcObjShape);
Base::Vector3d directionVector(0,0,1);
if (pcObjDir)
directionVector = static_cast<Base::VectorPy*>(pcObjDir)->value();
if (extractionTypePy && string(extractionTypePy) == "ShowHiddenLines")
extractionType = ProjectionAlgos::WithHidden;
if (vStylePy)
copy(Py::Dict(vStylePy), inserter(vStyle, vStyle.begin()));
if (v0StylePy)
copy(Py::Dict(v0StylePy), inserter(v0Style, v0Style.begin()));
if (v1StylePy)
copy(Py::Dict(v1StylePy), inserter(v1Style, v1Style.begin()));
if (hStylePy)
copy(Py::Dict(hStylePy), inserter(hStyle, hStyle.begin()));
if (h0StylePy)
copy(Py::Dict(h0StylePy), inserter(h0Style, h0Style.begin()));
if (h1StylePy)
copy(Py::Dict(h1StylePy), inserter(h1Style, h1Style.begin()));
// Execute the SVG generation
ProjectionAlgos Alg(pShape->getTopoShapePtr()->getShape(),
directionVector);
Py::String result(Alg.getSVG(extractionType, tol,
vStyle, v0Style, v1Style,
hStyle, h0Style, h1Style));
return result;
}
示例3: module
QMap<QString, CallTip> CallTipsList::extractTips(const QString& context) const
{
Base::PyGILStateLocker lock;
QMap<QString, CallTip> tips;
if (context.isEmpty())
return tips;
try {
Py::Module module("__main__");
Py::Dict dict = module.getDict();
#if 0
QStringList items = context.split(QLatin1Char('.'));
QString modname = items.front();
items.pop_front();
if (!dict.hasKey(std::string(modname.toLatin1())))
return tips; // unknown object
// get the Python object we need
Py::Object obj = dict.getItem(std::string(modname.toLatin1()));
while (!items.isEmpty()) {
QByteArray name = items.front().toLatin1();
std::string attr = name.constData();
items.pop_front();
if (obj.hasAttr(attr))
obj = obj.getAttr(attr);
else
return tips;
}
#else
// Don't use hasattr & getattr because if a property is bound to a method this will be executed twice.
PyObject* code = Py_CompileString(static_cast<const char*>(context.toLatin1()), "<CallTipsList>", Py_eval_input);
if (!code) {
PyErr_Clear();
return tips;
}
PyObject* eval = 0;
if (PyCode_Check(code)) {
eval = PyEval_EvalCode(reinterpret_cast<PyCodeObject*>(code), dict.ptr(), dict.ptr());
}
Py_DECREF(code);
if (!eval) {
PyErr_Clear();
return tips;
}
Py::Object obj(eval, true);
#endif
// Checks whether the type is a subclass of PyObjectBase because to get the doc string
// of a member we must get it by its type instead of its instance otherwise we get the
// wrong string, namely that of the type of the member.
// Note: 3rd party libraries may use their own type object classes so that we cannot
// reliably use Py::Type. To be on the safe side we should use Py::Object to assign
// the used type object to.
//Py::Object type = obj.type();
Py::Object type(PyObject_Type(obj.ptr()), true);
Py::Object inst = obj; // the object instance
union PyType_Object typeobj = {&Base::PyObjectBase::Type};
union PyType_Object typedoc = {&App::DocumentObjectPy::Type};
union PyType_Object basetype = {&PyBaseObject_Type};
if (PyObject_IsSubclass(type.ptr(), typedoc.o) == 1) {
// From the template Python object we don't query its type object because there we keep
// a list of additional methods that we won't see otherwise. But to get the correct doc
// strings we query the type's dict in the class itself.
// To see if we have a template Python object we check for the existence of supportedProperties
if (!type.hasAttr("supportedProperties")) {
obj = type;
}
}
else if (PyObject_IsSubclass(type.ptr(), typeobj.o) == 1) {
obj = type;
}
else if (PyInstance_Check(obj.ptr())) {
// instances of old style classes
PyInstanceObject* inst = reinterpret_cast<PyInstanceObject*>(obj.ptr());
PyObject* classobj = reinterpret_cast<PyObject*>(inst->in_class);
obj = Py::Object(classobj);
}
else if (PyObject_IsInstance(obj.ptr(), basetype.o) == 1) {
// New style class which can be a module, type, list, tuple, int, float, ...
// Make sure it's not a type objec
union PyType_Object typetype = {&PyType_Type};
if (PyObject_IsInstance(obj.ptr(), typetype.o) != 1) {
// this should be now a user-defined Python class
// http://stackoverflow.com/questions/12233103/in-python-at-runtime-determine-if-an-object-is-a-class-old-and-new-type-instan
if (Py_TYPE(obj.ptr())->tp_flags & Py_TPFLAGS_HEAPTYPE) {
obj = type;
}
}
}
// If we have an instance of PyObjectBase then determine whether it's valid or not
if (PyObject_IsInstance(inst.ptr(), typeobj.o) == 1) {
Base::PyObjectBase* baseobj = static_cast<Base::PyObjectBase*>(inst.ptr());
const_cast<CallTipsList*>(this)->validObject = baseobj->isValid();
}
else {
// PyObject_IsInstance might set an exception
PyErr_Clear();
//.........这里部分代码省略.........
示例4: approxSurface
Py::Object approxSurface(const Py::Tuple& args, const Py::Dict& kwds)
{
PyObject *o;
// spline parameters
int uDegree = 3;
int vDegree = 3;
int uPoles = 6;
int vPoles = 6;
// smoothing
PyObject* smooth = Py_True;
double weight = 0.1;
double grad = 1.0; //0.5
double bend = 0.0; //0.2
// other parameters
int iteration = 5;
PyObject* correction = Py_True;
double factor = 1.0;
static char* kwds_approx[] = {"Points", "UDegree", "VDegree", "NbUPoles", "NbVPoles",
"Smooth", "Weight", "Grad", "Bend",
"Iterations", "Correction", "PatchFactor", NULL};
if (!PyArg_ParseTupleAndKeywords(args.ptr(), kwds.ptr(), "O|iiiiO!dddiO!d",kwds_approx,
&o,&uDegree,&vDegree,&uPoles,&vPoles,
&PyBool_Type,&smooth,&weight,&grad,&bend,
&iteration,&PyBool_Type,&correction,&factor))
throw Py::Exception();
double curvdiv = 1.0 - (grad + bend);
int uOrder = uDegree + 1;
int vOrder = vDegree + 1;
// error checking
if (grad < 0.0 || grad > 1.0) {
throw Py::ValueError("Value of Grad out of range [0,1]");
}
if (bend < 0.0 || bend > 1.0) {
throw Py::ValueError("Value of Bend out of range [0,1]");
}
if (curvdiv < 0.0 || curvdiv > 1.0) {
throw Py::ValueError("Sum of Grad and Bend out of range [0,1]");
}
if (uDegree < 1 || uOrder > uPoles) {
throw Py::ValueError("Value of uDegree out of range [1,NbUPoles-1]");
}
if (vDegree < 1 || vOrder > vPoles) {
throw Py::ValueError("Value of vDegree out of range [1,NbVPoles-1]");
}
try {
Py::Sequence l(o);
TColgp_Array1OfPnt clPoints(0, l.size()-1);
if (clPoints.Length() < uPoles * vPoles) {
throw Py::ValueError("Too less data points for the specified number of poles");
}
int index=0;
for (Py::Sequence::iterator it = l.begin(); it != l.end(); ++it) {
Py::Tuple t(*it);
clPoints(index++) = gp_Pnt(
(double)Py::Float(t.getItem(0)),
(double)Py::Float(t.getItem(1)),
(double)Py::Float(t.getItem(2)));
}
Reen::BSplineParameterCorrection pc(uOrder,vOrder,uPoles,vPoles);
Handle_Geom_BSplineSurface hSurf;
pc.EnableSmoothing(PyObject_IsTrue(smooth) ? true : false, weight, grad, bend, curvdiv);
hSurf = pc.CreateSurface(clPoints, iteration, PyObject_IsTrue(correction) ? true : false, factor);
if (!hSurf.IsNull()) {
return Py::asObject(new Part::BSplineSurfacePy(new Part::GeomBSplineSurface(hSurf)));
}
throw Py::RuntimeError("Computation of B-Spline surface failed");
}
catch (Standard_Failure &e) {
std::string str;
Standard_CString msg = e.GetMessageString();
str += typeid(e).name();
str += " ";
if (msg) {str += msg;}
else {str += "No OCCT Exception Message";}
throw Py::RuntimeError(str);
}
catch (const Base::Exception &e) {
throw Py::RuntimeError(e.what());
}
catch (...) {
throw Py::RuntimeError("Unknown C++ exception");
}
}
示例5: meshFromShape
Py::Object meshFromShape(const Py::Tuple& args, const Py::Dict& kwds)
{
PyObject *shape;
static char* kwds_maxLength[] = {"Shape", "MaxLength",NULL};
PyErr_Clear();
double maxLength=0;
if (PyArg_ParseTupleAndKeywords(args.ptr(), kwds.ptr(), "O!d", kwds_maxLength,
&(Part::TopoShapePy::Type), &shape, &maxLength)) {
MeshPart::Mesher mesher(static_cast<Part::TopoShapePy*>(shape)->getTopoShapePtr()->getShape());
mesher.setMethod(MeshPart::Mesher::Mefisto);
mesher.setMaxLength(maxLength);
mesher.setRegular(true);
return Py::asObject(new Mesh::MeshPy(mesher.createMesh()));
}
static char* kwds_maxArea[] = {"Shape", "MaxArea",NULL};
PyErr_Clear();
double maxArea=0;
if (PyArg_ParseTupleAndKeywords(args.ptr(), kwds.ptr(), "O!d", kwds_maxArea,
&(Part::TopoShapePy::Type), &shape, &maxArea)) {
MeshPart::Mesher mesher(static_cast<Part::TopoShapePy*>(shape)->getTopoShapePtr()->getShape());
mesher.setMethod(MeshPart::Mesher::Mefisto);
mesher.setMaxArea(maxArea);
mesher.setRegular(true);
return Py::asObject(new Mesh::MeshPy(mesher.createMesh()));
}
static char* kwds_localLen[] = {"Shape", "LocalLength",NULL};
PyErr_Clear();
double localLen=0;
if (PyArg_ParseTupleAndKeywords(args.ptr(), kwds.ptr(), "O!d", kwds_localLen,
&(Part::TopoShapePy::Type), &shape, &localLen)) {
MeshPart::Mesher mesher(static_cast<Part::TopoShapePy*>(shape)->getTopoShapePtr()->getShape());
mesher.setMethod(MeshPart::Mesher::Mefisto);
mesher.setLocalLength(localLen);
mesher.setRegular(true);
return Py::asObject(new Mesh::MeshPy(mesher.createMesh()));
}
static char* kwds_deflection[] = {"Shape", "Deflection",NULL};
PyErr_Clear();
double deflection=0;
if (PyArg_ParseTupleAndKeywords(args.ptr(), kwds.ptr(), "O!d", kwds_deflection,
&(Part::TopoShapePy::Type), &shape, &deflection)) {
MeshPart::Mesher mesher(static_cast<Part::TopoShapePy*>(shape)->getTopoShapePtr()->getShape());
mesher.setMethod(MeshPart::Mesher::Mefisto);
mesher.setDeflection(deflection);
mesher.setRegular(true);
return Py::asObject(new Mesh::MeshPy(mesher.createMesh()));
}
static char* kwds_minmaxLen[] = {"Shape", "MinLength","MaxLength",NULL};
PyErr_Clear();
double minLen=0, maxLen=0;
if (PyArg_ParseTupleAndKeywords(args.ptr(), kwds.ptr(), "O!dd", kwds_minmaxLen,
&(Part::TopoShapePy::Type), &shape, &minLen, &maxLen)) {
MeshPart::Mesher mesher(static_cast<Part::TopoShapePy*>(shape)->getTopoShapePtr()->getShape());
mesher.setMethod(MeshPart::Mesher::Mefisto);
mesher.setMinMaxLengths(minLen, maxLen);
mesher.setRegular(true);
return Py::asObject(new Mesh::MeshPy(mesher.createMesh()));
}
#if defined (HAVE_NETGEN)
static char* kwds_fineness[] = {"Shape", "Fineness", "SecondOrder", "Optimize", "AllowQuad",NULL};
PyErr_Clear();
int fineness=0, secondOrder=0, optimize=1, allowquad=0;
if (PyArg_ParseTupleAndKeywords(args.ptr(), kwds.ptr(), "O!i|iii", kwds_fineness,
&(Part::TopoShapePy::Type), &shape, &fineness,
&secondOrder, &optimize, &allowquad)) {
MeshPart::Mesher mesher(static_cast<Part::TopoShapePy*>(shape)->getTopoShapePtr()->getShape());
mesher.setMethod(MeshPart::Mesher::Netgen);
mesher.setFineness(fineness);
mesher.setSecondOrder(secondOrder > 0);
mesher.setOptimize(optimize > 0);
mesher.setQuadAllowed(allowquad > 0);
return Py::asObject(new Mesh::MeshPy(mesher.createMesh()));
}
static char* kwds_user[] = {"Shape", "GrowthRate", "SegPerEdge", "SegPerRadius", "SecondOrder", "Optimize", "AllowQuad",NULL};
PyErr_Clear();
double growthRate=0, nbSegPerEdge=0, nbSegPerRadius=0;
if (PyArg_ParseTupleAndKeywords(args.ptr(), kwds.ptr(), "O!|dddiii", kwds_user,
&(Part::TopoShapePy::Type), &shape,
&growthRate, &nbSegPerEdge, &nbSegPerRadius,
&secondOrder, &optimize, &allowquad)) {
MeshPart::Mesher mesher(static_cast<Part::TopoShapePy*>(shape)->getTopoShapePtr()->getShape());
mesher.setMethod(MeshPart::Mesher::Netgen);
mesher.setGrowthRate(growthRate);
mesher.setNbSegPerEdge(nbSegPerEdge);
mesher.setNbSegPerRadius(nbSegPerRadius);
mesher.setSecondOrder(secondOrder > 0);
mesher.setOptimize(optimize > 0);
mesher.setQuadAllowed(allowquad > 0);
return Py::asObject(new Mesh::MeshPy(mesher.createMesh()));
}
#endif
PyErr_Clear();
//.........这里部分代码省略.........
示例6: sysmod
//.........这里部分代码省略.........
// by e.g. LiquidWeather and those attr is missing in StringIO
// and cause it's buildin we can't just add it but would need to
// implement our own class. Grrrr, what a stupid design :-/
//"try:\n"
//" import cStringIO\n"
//" sys.stdin = cStringIO.StringIO()\n"
//"except:\n"
//" pass\n"
// Class to redirect something. We use this class e.g. to redirect
// <stdout> and <stderr> to a c++ event.
//"class Redirect:\n"
//" def __init__(self, target):\n"
//" self.target = target\n"
//" def write(self, s):\n"
//" self.target.call(s)\n"
// Wrap builtin __import__ method. All import requests are
// first redirected to our PythonModule.import method and
// if the call returns None, then we call the original
// python import mechanism.
"import __builtin__\n"
"import __main__\n"
"import traceback\n"
"sys.modules['_oldmain'] = sys.modules['__main__']\n"
"_main_builtin_import_ = __main__.__builtin__.__import__\n"
"class _Importer:\n"
" def __init__(self, script):\n"
" self.script = script\n"
" self.realImporter = __main__.__builtin__.__import__\n"
" __main__.__builtin__.__import__ = self._import\n"
" def _import(self, name, globals=None, locals=None, fromlist=[], level = -1):\n"
//" try:\n"
//" print \"1===========> _Importer name=%s fromlist=%s\" % (name,fromlist)\n"
#if PY_MAJOR_VERSION >= 3 || (PY_MAJOR_VERSION >= 2 && PY_MINOR_VERSION >= 5)
" mod = __main__._import(self.script, name, globals, locals, fromlist, level)\n"
#else
" mod = __main__._import(self.script, name, globals, locals, fromlist)\n"
#endif
" if mod == None:\n"
" if name == 'qt':\n"
" raise ImportError('Import of the PyQt3 module is not allowed. Please use PyQt4 instead.')\n"
" if name == 'dcop':\n"
" raise ImportError('Import of the KDE3 DCOP module is not allowed. Please use PyQt4 DBUS instead.')\n"
#if PY_MAJOR_VERSION >= 3 || (PY_MAJOR_VERSION >= 2 && PY_MINOR_VERSION >= 5)
" mod = self.realImporter(name, globals, locals, fromlist, level)\n"
#else
" mod = self.realImporter(name, globals, locals, fromlist)\n"
#endif
" if mod != None:\n"
//" print \"3===========> _Importer name=%s fromlist=%s\" % (name,fromlist)\n"
" if globals != None and (not fromlist or len(fromlist)==0 or '*' in fromlist):\n"
" globals[name] = mod\n"
" return mod\n"
//" except ImportError:\n"
//" except:\n"
//" print \"9===========> _Importer Trying ImportError with name=%s fromlist=%s insysmodules=%s\" % (name,fromlist,name in sys.modules)\n"
//" print \" \".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) )\n"
//" return None\n"
/*
" print \"_Importer name=%s fromlist=%s\" % (name,fromlist)\n"
" if fromlist == None:\n"
" mod = __main__._import(self.script, name, globals, locals, fromlist)\n"
" if mod != None:\n"
" print \"2===========> _Importer name=%s fromlist=%s\" % (name,fromlist)\n"
" globals[name] = mod\n"
" return mod\n"
//" if name in sys.modules:\n" // hack to preserve module paths, needed e.g. for "import os.path"
//" print \"3===========> _Importer name=%s fromlist=%s\" % (name,fromlist)\n"
//" return sys.modules[name]\n"
" print \"3===========> _Importer Trying realImporter with name=%s fromlist=%s insysmodules=%s\" % (name,fromlist,name in sys.modules)\n"
" try:\n"
" mod = self.realImporter(name, globals, locals, fromlist)\n"
" print \"4===========> _Importer Trying realImporter with name=%s fromlist=%s insysmodules=%s module=%s\" % (name,fromlist,name in sys.modules,mod)\n"
//" mod.__init__(name)\n"
//" globals[name] = mod\n"
//" sys.modules[name] = mod\n"
" print \"5===========> _Importer Trying realImporter with name=%s fromlist=%s insysmodules=%s module=%s\" % (name,fromlist,name in sys.modules,mod)\n"
" return mod\n"
" except ImportError:\n"
" print \"6===========> _Importer Trying ImportError with name=%s fromlist=%s insysmodules=%s\" % (name,fromlist,name in sys.modules)\n"
" n = name.split('.')\n"
" if len(n) >= 2:\n"
" print \"7===========> _Importer Trying ImportError with name=%s fromlist=%s insysmodules=%s\" % (name,fromlist,name in sys.modules)\n"
" m = self._import(\".\".join(n[:-1]),globals,locals,[n[-1],])\n"
" print \"8===========> _Importer Trying ImportError with name=%s fromlist=%s insysmodules=%s\" % (name,fromlist,name in sys.modules)\n"
" return self.realImporter(name, globals, locals, fromlist)\n"
" print \"9===========> _Importer Trying ImportError with name=%s fromlist=%s insysmodules=%s\" % (name,fromlist,name in sys.modules)\n"
" raise\n"
*/
;
PyObject* pyrun = PyRun_String(s.toLatin1().data(), Py_file_input, moduledict.ptr(), moduledict.ptr());
if(! pyrun) {
Py::Object errobj = Py::value(Py::Exception()); // get last error
setError( QString("Failed to prepare the __main__ module: %1").arg(errobj.as_string().c_str()) );
}
Py_XDECREF(pyrun); // free the reference.
}