Also on collabedit with highlighting: http://collabedit.com/mj742
//cTest.cnote: PSF recommends compiling these using disutils instead. I'm sharing this because of my interest in how the low-level interaction works.
#include
//an example method:
static PyObject* py_double(PyObject* self, PyObject* args){
//self is always here, but only used if it's an
//instance method.
int a; PyArg_ParseTuple(args, "i:py_double", &a); //"i:py_double": i for extract one int. // Py_Arg_ParseTuple(args, "isfo:py_double", &a, &b, &c, &d); // would extract an (i)nt, (s)tring, (f)loat, Py_(O)bject // to a, b, c, d respectively. // After the colon is a string used for exception printouts // so if this causes an error we'll know it came from here. return PyInt_FromLong(a * 2);
}
//table of methods to include in this module:
//it's an array of type struct PyMethodDef.
static PyMethodDef test_functions[] = {/*{python name, c pointer to func, arg format, doc string},*/ {"doubler", py_double, METH_VARARGS, "doubles an int"}, {NULL, NULL, 0, NULL}//sentinal value
};
//This functions is called by Python when you import the module:
//this macro handles void + extern for python module init functions:
PyMODINIT_FUNC
initcTest(void){Py_InitModule("cTest", test_functions); //params: module name, method list
}
/*
The name (here cTest) must be consitent in:
1. the filename cTest.pyd (Windows) or cTest.so (Linux)
2. the init method initcTest(void)
3. the first parameter to Py_InitModule("cTest", test_funtions).
note that the name does not have to start with 'c'.
Compiling:
Windows & MSVC:
I use the Visual Studio Command Prompt. These things can also be
configured in the IDE.
1.configure your environment so that the Include path
includes c:\python26\Include (change this for your python location.
Where ever Python.h is). Using the Visual Studio Command Prompt:
> set include=d:\python26\include;%include%
2.compile this to a .dll. Using the Visual Studio Command Prompt:
>cl cTest.c /LD
3.rename it to cTest.pyd
>move cTest.dll cTest.pyd
4.try it in Python!
>python
Python x.y blah blah blah
>>>import cTest
>>>cTest.doubler(3)
6
>>>
Linux & gcc:
1.build an object file:
$gcc -c cTest.c -I/usr/include/python2.6
(change this for your Python include location, where ever Python.h
is.) Note: sometimes Python is installed without the header files.
in Ubuntu you need to get the Python-Dev repository.
2.create a static library:
$ar rcs libcTest.a cTest.o
3.make a shared library:
$gcc -shared -W1,-soname,libcTest.so.1 cTest.o
4.try it in Python!
$python
Python x.y blah blah blah
>>>import cTest
>>>cTest.doubler(3)
6
>>>
*/
No comments:
Post a Comment