problem using C-bindings

eq eq at eq.homelinux.org
Thu Aug 19 16:32:15 EDT 2004


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")

The Python-code would look like this:
MyClass.py:

class MyClass:
	def MyFunction(self):
		print 'Hello'

My C-application can do all the steps except the last one.
myapp.c:

#include <Python.h>

static PyMethodDef ModuleMethods[] = { {NULL} };

void attachFunc(PyObject* class,PyObject* dict,char* func_code,char* name)
{
	PyObject* pyfunc_code;
	PyObject* pyfunc;
	pyfunc_code=Py_CompileString(func_code,"",Py_file_input);
	pyfunc=PyFunction_New(pyfunc_code,dict);
	PyObject_SetAttrString(class,name,pyfunc);
}

int main(int argc,char** argv)
{
	Py_SetProgramName(argv[0]);
	Py_Initialize();
	PyObject* module;
	PyObject* module_dict;
	PyObject* class;
	PyObject* class_dict;
	PyObject* class_name;
	
	module=Py_InitModule("MyModule",ModuleMethods);
	module_dict=PyModule_GetDict(module);
	class_dict=PyDict_New();
	class_name=PyString_FromString("MyClass");
	class=PyClass_New(NULL,class_dict,class_name);
	PyDict_SetItemString(module_dict,"MyClass",class);
	
	attachFunc(class,module_dict,"print 'hello'\n","MyFunction");
	
	PyRun_SimpleString("import MyModule\n");
	PyRun_SimpleString("t=MyModule.MyClass()\n");
	PyRun_SimpleString("t.MyFunction()\n");
	return 0;
}

When executing the application, I get the following(because of the
"t.MyFunction()") Traceback (most recent call last):
  File "<string>", line 1, in ?
TypeError: ?() takes no arguments (1 given)

What am I doing wrong?

Greetings,
Henning



More information about the Python-list mailing list