1

I'm making a python extension module using my C++ code and I've made a struct that I use to pass my C++ variables. I want some of those variables to be inaccessible from the python level. How can I do that?

    typedef struct {
        PyObject_HEAD
        std::string region;
        std::string stream;

        bool m_is_surface = false;
        bool m_is_stream = false;
    } PyType;

I want m_is_surface and m_is_stream to be inaccessible by the user. Only PyType's methods should access it. So the and user CAN'T do something like this:

import my_module

instance = my_module.PyType()
instance.m_is_surface = False # This should raise an error. Or preferably the user can't see this at all

I cannot just add private to the struct because python type members are created as a standalone function and is linked to the type later on, so I cannot access them inside the struct's methods. So if I say:


 int PyType_init(PyType *self, PyObject *args, PyObject *kwds)
    {
        static char *kwlist[] = {"thread", "region", "stream", NULL};
        PyObject *tmp;


        if (!PyArg_ParseTupleAndKeywords(args, kwds, "bs|s", kwlist,
                                        &self->thread, &self->region, &self->stream))
            return -1;
        
        return 0;
    }

It will raise an is private within this context error.

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
Turgut
  • 711
  • 3
  • 25

1 Answers1

1

You should do nothing. Unless you create an accessor property these attributes are already inaccessible from Python. Python cannot automatically see C/C++ struct members.

DavidW
  • 29,336
  • 6
  • 55
  • 86
  • So if I do not add them to `PyStructMembers` will I still be able to use them regardless? – Turgut Dec 02 '22 at 06:40
  • 1
    I don't know what you mean by `PyStructMembers`, but `PyMemberDef`/`PyGetSetDef` are only there to expose things to Python. You can use them in C or C++ fine without – DavidW Dec 02 '22 at 07:19