problem using C-bindings

eq eq at eq.homelinux.org
Fri Aug 20 12:10:22 CEST 2004


Am Thu, 19 Aug 2004 19:21:31 -0400 schrieb Jack Diederich:

> On Fri, Aug 20, 2004 at 12:14:05AM +0200, eq wrote:
>> Am Thu, 19 Aug 2004 17:45:45 -0400 schrieb Jack Diederich:
>> 
>> > On Thu, Aug 19, 2004 at 10:32:15PM +0200, eq wrote:
>> >> Hi,
>> >> 
>> >> I'm trying to create a program(written in C) that does the following
>> >> things using embedded Python:
>> >> 1. Create a module(say, "MyModule")
>> >> 2. Create a class in that module(say, "MyClass")
>> >> 3. Create a function in that module(say, "MyFunction")
>> > [snip]
>> >> 	class_dict=PyDict_New();
>> >> 	class_name=PyString_FromString("MyClass");
>> >> 	class=PyClass_New(NULL,class_dict,class_name);
>> >> 	PyDict_SetItemString(module_dict,"MyClass",class);
>> > [snip]
>> > 
>> > Take a look at Modules/xxsubtype.c in the source distribution.
>> > It is an example of how to subtype a builtin.  xxmodule.c shows
>> > how to make a class from scratch.  Both are out of date but a good
>> > sarting spot.
>> > 
>> Hm, perhaps I over-complicated my problem:
>> I don't need a full python-class in pure C. I just need to create a
>> (python!) function(a dynamic one, not a static C function) and attach it
>> to an already existing python-class just by using C-calls.
>> I try to do this by compiling the function's code with:
>> 
>> pyfunc_code=Py_CompileString(func_code,"",Py_file_input);
>> 
>> where func_code could be something like "print 'hello'" and then I try to
>> make a function out of this by calling:
>> 
>> pyfunc=PyFunction_New(pyfunc_code,dict);
>> 
>> where dict is the global namespace for the function.
>> What I now want is to attach this function to the already created class
>> "MyClass".
>> 
> 
> In that case I would see how xxmodule.c exports methods in the xx_methods
> array and then in your python code have the class method call that exported
> method.

That's not the point, the problem is that no example i've found(including
the xx_* files) shows how to create a python function from C-code. To make
the thing worse, there's also no example how to add such a function to a
class by using C code.
The xx_* files only create static C methods what is not what I want.

> 
> import xxmodule
> class MyClass(object):
>   def xxfunc(self, arg):
>     return xxmodule.xxfunc(self.someval, arg)
> 
> In practice I've never had a class that wasn't all python or all C but
> I have written small helper functions in C that are called from python.
> 
> -Jack





More information about the Python-list mailing list