Python array --> C
Gordon McMillan
gmcm at hypernet.com
Wed Jul 7 11:04:15 EDT 1999
Randy Heiland writes:
> Gordon McMillan wrote:
>
> > Randy Heiland writes:
...
> > > From main(), I would like to invoke xyzzy.foo() and get this array
> > > of unsigned chars into a C array. How do I do this? I assume I'll
> > > need to use PyRun_String(...) somehow - true?
> >
> > Not at all. You'll want to use PyString methods to get its size and
> > char *, etc. You can use python as a lib without ever involving the
> > interpreter. See the C API reference manual (and be prepared to grep
> > the objects and modules subdirectories).
...
> Can you please be more specific (sorry, I need a lot of
> hand-holding). Exactly what PyString method would I call in main()
> to (1) invoke the xyzzy.foo() method and (2) get the resulting byte
> array into a C array?
In Python, you would first "import xyzzy", right? The C API docs
mention PyImport_ImportModule(). So we grep and see it should look
like:
module = PyImport_ImportModule("xyzzy");
....
func = PyObject_GetAttrString(module, "foo");
....
PyObject *res = PyObject_CallFunction(func, ...);
Now you should probably do
if (PyString_Check(res)) {
int sz = PyString_Size(res);
char *p = PyString_AsString(res);
memcpy(myarray, p, sz);
...
}
I've left out error handling and the all important refcounting.
Basically it's a matter of figuring out what would happen in Python,
looking through the C API docs, and using grep to find examples.
Pretty soon you'll realize it's a lot more fun to write it in pure
Python <wink>.
- Gordon
More information about the Python-list
mailing list