[email protected]
[Top] [All Lists]

[C++-sig] How to implement a cross-module C-API

Subject: [C++-sig] How to implement a cross-module C-API
From: Thomas Schipolowski
Date: Mon, 05 Sep 2005 16:36:17 +0200

I have a working C++ extension module for python that has been exported 
with boost::python. Now I am trying to embed the python interpreter in a 
plain C program and make it execute a script which will import my C++ 
module and do some calculations with it. The results will end up in a 
C++ object created by the extension module. In the enveloping C program, 
I would be able to retrieve a PyObject* reference to the Python wrapper 
of this result object from the interpreter global namespace after the 
script finished. But is there a way to get fast C-level access to the 
underlying C++ object?

I read the extending/embedding part of the standard python docu and 
tried to think up a possible solution. As it seems to be a bit involved, 
can please somebody tell me if I am on the right way, or what I could do 


My idea so far:

I would add some free functions to my C++ module that offer a minimal 
C-API for some of the classes defined there. These functions would 
accept a PyObject* reference as argument. Internally, they would 
construct a boost::python::object from the PyObject* and try to extract 
the expected C++ object type from it. Once I have the C++ object back, I 
could call its methods to perform the desired operations. All results 
would be returned as plain C structs or arrays.

In order to get access to the API functions in my C program, I would 
package them in a static table of function pointers, place a void* ptr 
to the table in a Python CObject, and make the CObject visible to my C 
program by exporting a function (to python) that delivers the CObject on 

Can this work? The fact that there is a "extern C" declaration for using 
C functions in C++ makes me wonder if it is possible/safe to access a 
function compiled with C++ from a program compiled with a C compiler?


Thanks in advance,


C++-sig mailing list
[email protected]

<Prev in Thread] Current Thread [Next in Thread>