Danny Holstein
Danny Holstein

Reputation: 174

what is the python C api function that returns a PyObject using the object name

I'm embedding Python into my C++ and creating PyObjects 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

Answers (1)

Mechanic Pig
Mechanic Pig

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:

  1. Use PyEval_GetGlobals to get the global namespace.
  2. Use PyUnicode_FromString to construct a string object through a C string.
  3. Use 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

Related Questions