Extending back to the embedder

David Brady daves_spam_dodging_account at yahoo.com
Fri Oct 19 15:07:03 EDT 2001


Hello all,

I am trying to use Python as a macro language for my
application (written in MFC/C++).  What I would like
to do is allow users to write short scripts in Python
that can control the parent application.

I have successfully written a trivial embedding app,
and a trivial extension app.  What I don't understand
clearly is how to compile an extension so that Python
could call back into the parent application.

What I have now is a C app that can call Python, which
can invoke C code in another library apart from my
app.  Forgive my terrible ASCII UML:

+---+    +--------+    +---+
| C |--->| Python |--->| C +
+---+    +--------+    +---+


When what I really want is

+---+    +--------+
| C |--->| Python |
|   |<---|        |
+---+    +--------+

I understand how to register a Python object at
runtime in C so that C can call back into an object
that was created by a user after my app was written. 
What I would like to do is go the other way: be able
to register a C function with Python so that it can
call C back at runtime.  Actually, that's a bit
misleading.  I do not need to access C functions
written after my embedding/extending work is done.  I
have a fixed C interface that I want Python to
interact with.

What I want, I guess, is a way to embed Python, and
give the embedded Python access to some of my C
functions.

So... how would I go about this?  Is there a way to
compile my entire app so that it behaves like an
extension to the embedded Python interpreter?  Or do I
need to extend out into a .dll that hunts down the
parent app?

Thank you for your time.

Oh, for simplicity, here's a example code for us all
to share.  This is just trivial examples of what I
want to do, if my whole approach is wrong (like
returning a char* instead of modifying a char*
argument) let me know.  Imagine I have C++ code to get
the ID number of the current document, and to set the
name of a given document.  I also have a button named
"Foo" on the App that runs the python code
"UserMacroFoo" when it is clicked.  UserMacroFoo will
try to set the name of the active document to "Foo!":

// C++ code:
int GetActiveDocument( void );
void SetDocumentName( int DocID, char* Name );

//...
void Foo_OnClick()
{
    PyObject *pModule, *pFunction, *pResult;
    pModule = PyImport_ImportModule( "UserMacros" );
    pFunction = PyObject_GetAttrString(pmod,
"UserMacroFoo");
    pResult = PyEval_CallObject(pfunc, NULL);
}

# Python code
def UserMacroFoo():
    i = App.GetActiveDocument()
    App.SetDocumentName( i, "Foo!" )
    
Thank you in advance,

-dB
--
David Brady
daves_spam_dodging_account at yahoo.com
I'm feeling very surreal today... or *AM* I?

__________________________________________________
Do You Yahoo!?
Make a great connection at Yahoo! Personals.
http://personals.yahoo.com




More information about the Python-list mailing list