Hi, I am trying to create an extension to call into a c++ library, a library which simply returns a string, given a string. At first, a quick and simple approach was tried (based on post http://stackoverflow.com/questions/1615813/how-to-use-c-classes-with-ctypes) in which the usual infrastructure for loading extensions is bypassed. A working simple example is shown beneath:
myextension.cpp #include <python.h> extern "C" { int test_func() { return 10; } } To execute in Python: from ctypes import cdll mlib=cdll.LoadLibrary("myextension.dll") print( mlib.test_func() ) This works fine when function return type is a number, but not when a string. C++ code returns char *, which is received by Python as a pointer, which prints as a number, eg1755066468. Apparently, based on web posts viewed, it seems data conversion is required, using a function such as Py_BuildValue("s", str) from python.h. But this gave a similar result, in which a pointer is received by Python instead of a string. The modified function used in this case: PyObject * test_func() { return Py_BuildValue("s", "aString"); } Resort was then made to the conventional approach of defining a method table and initializing method. (Abandoned cdll.LoadLibrary(...) as subsequently test_func was not recognised, and instead put the dll (.dll changed to pyd) in /python26/DLLs.) The revised code: myextension.cpp #include <python.h> extern "C" { static PyObject * test_func(PyObject *self, PyObject *args) { return (PyObject *) 0; } static PyMethodDef TestMethods[] = { {"test", test_func, METH_VARARGS, "test"}, {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC initlibTestExtnModule(void) { (void) Py_InitModule("TestExtnModule", TestMethods); } } Using the import statement "import libTestExtnModule" however produced the following error message: "SystemError: dynamic module not initialized properly" As far as I know there is nothing wrong with the initialisation of the extension code above. Perhaps the error is related to compilation. I have not used distutils, but rather compiled externally and dropped the dll (as pyd) into the /DLLs directory as mentioned. This should work, as far as I know. Related to compilation, both MinGW and Python2.6 are 32 bit versions, and g++ statements used were: mingw32-g++ "-IC:\\Python26\\include" -O0 -g3 -Wall -c -fmessage-length=0 -o myextension.o "..\\myextension.cpp" mingw32-g++ -LC:/Python26/libs -shared -o libTestExtnModule.pyd myextension.o -lpython26 Any suggestions as to why the dynamic module is not initialising properly, or as to how otherwise a string can be returned, would be greatly appreciated. Thanks Jason
-- http://mail.python.org/mailman/listinfo/python-list