How do I add method dynamically to module using C API?

Alf P. Steinbach /Usenet alf.p.steinbach+usenet at gmail.com
Wed Jul 7 22:57:13 EDT 2010


The code below, very much work in progress, just trying things, is C++.

Sorry about the formatting, I had to reformat manually for this posting:


<code>
     class Module
     {
     private:
         Ptr     p_;

     public:
         Module( PyModuleDef const& def )
             : p_( ::PyModule_Create( const_cast< PyModuleDef* >( &def ) ) )
         {
             (p_.get() != 0) || cppx::throwX( "Module::<init>: failed" );
         }

         PyObject* rawPtr() const    { return p_.get(); }
         PyObject* release()         { return p_.release(); }

         void setDocString( wchar_t const s[] )
         {
             Ptr const v = ::PyUnicode_FromWideChar( s, -1 );
             (v.get() != 0)
                 || cppx::throwX( "PyUnicode_FromWideChar failed" );
             int const _ = ::PyObject_SetAttrString(
                 p_.get(), "__doc__", v.get()
                 );
             (_ != -1 )
                 || cppx::throwX( "PyObject_SetAttrString failed" );
         }

         void setRoutine(
             char const name[], PyCFunction f, char const doc[] = ""
             )
         {
             PyMethodDef def = { name, f, METH_VARARGS, doc };

             Ptr const   pyName  = ::PyUnicode_FromString( name );
             Ptr         r       = ::PyCFunction_NewEx(
                 &def, p_.get(), pyName.get()
                 );

             int const _ = ::PyModule_AddObject( p_.get(), name, r.release() );
             (_ != -1 )
                 || cppx::throwX( "PyModule_AddObject failed" );
         }
     };
</code>


Problem: when a routine installed by 'setRoutine' above is called from Python, 
then it fails with e.g. "SystemError: Bad call flags in PyCFunction_Call. 
METH_OLDARGS is no longer supported!"

And since things work for a single method when I declare 'def' as 'static', I 
suspect that means that the function object created by PyCFunction_NewEx holds 
on to a pointer to the PyMethodDef structure?

I'm unable to find documentation of PyCFunction_NewEx, and more criticially, I'm 
unable to find any documented way to turn a C or C++ function into a Python 
function object?


Cheers,

- Alf

-- 
blog at <url: http://alfps.wordpress.com>



More information about the Python-list mailing list