Reputation: 174
I'm embedding Python into my C++ and creating PyObject
s to represent my data/objects (ints, doubles, strings, etcetera).
I've put in several hours trying to find the answer to the above question, I expected there'd be a "name" property or "name()" method to set, and reference, the canonical object name used in Python script (as global/local objects), that there'd be a function:
PyObject *PyObject_ByName(PyObject *PyObjs, char* name)
Return value: New reference. Part of the Stable ABI. Return a new PyObject reference from an array of PyObjs that match the 'name', or NULL on failure.
What am I missing? I see all the other pieces in place.
MSEXPORT PyObject* PyVariant(VarObj* data, tLvVarErr* error) {
PyObject* module_name, * module, * dict, * python_class, * object;
PyObject *pValue = NULL; // <- what I want to set name
switch (data->data.index())
{
case VarIdx::I32:
pValue = PyLong_FromLong((long) get<int32_t>(data->data));
break;
case VarIdx::DBL:
pValue = PyFloat_FromDouble ((double) get<double>(data->data));
break;
case VarIdx::Str :
pValue = PyUnicode_FromString((char*) get<string*>(data->data)->c_str());
break;
default:
return NULL;
}
return pValue;
}
Upvotes: 0
Views: 332
Reputation: 7736
What you need to know is that Python namespaces are implemented based on dictionaries (the exception is the local namespace inside the function). Global name lookup is just to obtain the global namespace dictionary and search through the string key. Therefore, what you need to do is:
PyEval_GetGlobals
to get the global namespace.PyUnicode_FromString
to construct a string object through a C string.PyDict_GetItem
to get object from the global namespace.As for the _PyDict_LoadGlobal
I mentioned in the comment area, it is an API used internally by Python to quickly load objects (starting with an underscore of function names). You should avoid using it when writing C extensions.
Upvotes: 1