Closest C++ Python interaction

David klesk at mixmail.com
Sat Oct 19 06:43:05 EDT 2002


Lets supose I have this in one .cpp file of my project:

include "classtwo.h"

class classone
{
private:
  classtwo *m_pClass;
  ...
  public:
    void SetClassTwo( classtwo *pClass ) { m_pClass = pClass; };
    int CallClassTwo( char *strMethod ) { if( m_pClass ) return 
m_pClass->Call( strMethod ); else return 0; };
} 

Then I use SWIG to make a wrap version of classtwo in python, so I can 
write this in my script.

#usesclasstwo.py

import pythonclasstwo

o = pythonclasstwo.classtwo()

#end of usesclasstwo

Then, my program in C++ would be something like this:

int WinMain( ... )
{
...
  Py_Initialize();
  pClassOne = new classone();
  PyRun_SimpleString("import usesclasstwo.py");
...
  pClassOne->CallClassTwo( "MethodFour");
...
}

So, an instance of classtwo is created in Python, although Swig has put 
in the o.this the representation of the class 

in a Python string, something like _d8023100_p_classtwo, and o.thisown is 
equal to 1, as the instance belongs to 

Python.

But the pClassOne that is an instance of classone, is created in C++, so 
the m_pClass attribute must be a pointer to 

a classtwo instance instead of a pointer to the PythonObject that 
represents the shadow class classtwo instance 

named o. So m_pClass must has the value of 0x0031208d, because Swig packs
(unpacks) the pointer this way.

The question is simple, how can I get this pointer by calling a function 
in Python of the style 

AttachClassTwoToClassOne( o ), that of course must be a wrap function of 
a C++ function.

And, in the other hand, how can I call form C to a method in the o 
instance, that is:
The function classtwo->Call(char* strMethod) must do the inverse 
conversion of the pointer, that is, get the pointer, 

pack in a Python string like Swig and get the Python Object that 
represents the shadow class classtwo instance 

corresponding to the packed pointer in the Python String (so I will get 
the o ), and then call the method and then get 

back the result.

How can I achieve the two things? I thingkthat the first problem is the 
most difficult, because the code of the 

classtwo class and the wrapper functions will be in a DLL.

I also need to know also how to call to the swig function that packs and 
unpacks pointers both for the first part of the 

problem and for the second one.

Thank you all, David.



More information about the Python-list mailing list