embedded python questions

Syver Enstad syver-en+usenet at online.no
Wed May 7 02:43:25 EDT 2003


db <dbunix at yahoo.com> writes:

> Hi,
> 
> Please CC me as Im not subscribed.
> 
> Is it possible to pass variables from C into an
> embedded Python interpreter and have them available
> from inside a script that gets executed via something
> similar to PyRun_SimpleFile()? 

Yes, but you can only pass Python objects into python code. In other
words, you have to create Python objects in your C code and then pass
them to python. The scenario you present is a quite typical one, you
will typically have to write a Python C extension type that enables python
to use your C object.

Like this:
// the module you want to pass your C extension type to
PyObject* module = PyImport_ImportModule("MyModule");
PyObject* entryFunction = PyObject_GetAttrString(module, "MyFunc");
// arg1 and arg2 would be data that you want to expose to Python in
// some fashion
PyObject* myextensionType = YouDefineThisFunction(arg1, arg2);
PyObject_CallFunction(entryFunction, "O", myExtensionType);

// NB, any error checking or reference counting is left out to make it
// simpler.


> For example, I want to
> be able to accept a socket connection in C, pass it
> into a python script, and have it available to the
> script when it executes.

For the socket example, there already exists a socket c module so you
should probably use that instead of writing your own wrapper.

-- 

Vennlig hilsen 

Syver Enstad




More information about the Python-list mailing list