Calling C functions from python

Calling C functions from Python

Written by Christian Stigen Larsen

License

Creative Commons License
This work is licensed under a Creative Commons Attribution-Share Alike 3.0 Unported License.

Here's a small tutorial on how to call your C functions from Python. You can also download this document as PDF.

Let's make some simple functions in C. We'll call the file myModule.c.

#include <Python.h>

/*
 * Function to be called from Python
 */
static PyObject* py_myFunction(PyObject* self, PyObject* args)
{
	char *s = "Hello from C!";
	return Py_BuildValue("s", s);
}

/*
 * Another function to be called from Python
 */
static PyObject* py_myOtherFunction(PyObject* self, PyObject* args)
{
	double x, y;
	PyArg_ParseTuple(args, "dd", &x, &y);
	return Py_BuildValue("d", x*y);
}

/*
 * Bind Python function names to our C functions
 */
static PyMethodDef myModule_methods[] = {
	{"myFunction", py_myFunction, METH_VARAGS},
	{"myOtherFunction", py_myOtherFunction, METH_VARARGS},
	{NULL, NULL}
};

/*
 * Python calls this to let us initialize our module
 */
void initmyModule()
{
	(void) Py_InitModule("myModule", myModule_methods);
}

Compiling dynamic libraries on Mac OS X is different from the usual gcc -shared you might be used to:

gcc -dynamiclib -I/usr/include/python2.3/ -lpython2.3 -o myModule.dylib myModule.c

Now you have to do something awkward; rename myModule.dylib to myModule.so, so that Python will find the correct file (this is a bug in Python, it should've been fixed, but that's as far as I know):

mv myModule.dylib myModule.so

If you are using a system that supports -shared you can simply do this:

gcc -shared -I/usr/include/python2.3/ -lpython2.3 -o myModule.so myModule.c

Here's a simple program in Python to call your functions:

from myModule import *

print "Result from myFunction:", myFunction()
print "Result from myOtherFunction(4.0, 5.0):", myOtherFunction(4.0, 5.0)

The output is:

Result from myFunction(): Hello from C!
Result from myOtherFunction(4.0, 5.0): 20.0

If you are going to make bigger libraries available from Python I suggest you check out SWIG.

转载于:https://www.cnblogs.com/rica/archive/2012/03/08/2385670.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值