Multiple program defined types -- access from C?

Michael P. Reilly arcege at shore.net
Wed Jul 7 11:45:08 EDT 1999


Gordon McMillan <gmcm at hypernet.com> wrote:
: Nathan Froyd wrote:
:> I'm writing a program that needs a lot of program-defined types that
:> are also exposed as python classes to the user. The problem is, I
:> also need to access the innards of a lot of these classes from C.
:> Are there any elegant ways to do this? It doesn't seem as though
:> Python likes for class functions to be used from outside the C file
:> they're defined in.

: Python asks you to declare almost everything as file static to reduce 
: the chance of name clashes when loaded dynamically in Unix (or maybe 
: I should say non-Windows, where this is not a problem).

: The "proper" way to make a C API available to other modules is to use 
: a CObject (see Extending / Embedding section 1.12) to pass a void * 
: around. If you're not trying to provide a C API to other extensions, 
: you can probably get away with losing the "static", as long as you're 
: careful about how you name your functions.

I'll just amend to this.  Nathan mentioned that his data types are also
Python data types.  To access the data from other modules, it may be
more appropriate to access the C data through the Python API
(PyObject_GetItem and/or PyObject_GetAttrString) than to always use
PyCObject objects.  This lets handles the conversion internally.

The PyCObject type is very useful, mainly (IMO) because you can
associate a string with it to help identify the contained data
(something that is difficult in other P* languages ;).

One thing to NOT do is use the C functions from one Python module in
another module.  Sharing C functions within different C files built into
one Python C module is fine, but nasty things can occur if used outside
of that module (in a UNIX dynamic library context anyway :).

  -Arcege





More information about the Python-list mailing list