0

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;
}
Danny Holstein
  • 144
  • 1
  • 14

1 Answers1

1

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.

Mechanic Pig
  • 6,756
  • 3
  • 10
  • 31
  • Okay, I still seem to be missing something, if we're embedding Python in C/C++, why wouldn't there be APIs to help me easily exchange data between C++ objects and Python objects? Am I trying to do this in a non-standard way? – Danny Holstein Sep 13 '22 at 15:05
  • 1
    2+3 can be combined into `PyDict_GetItemString` – DavidW Sep 14 '22 at 13:43