练习1、python在不使用import ctypes方式调用c语言动态库的练习,
第一步:做个c语言动态库,如果不使用ctypes方式,参考代码如下:
#include <Python.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int sum(int a,int b) #c语言实现的功能
{
return a+b;
}
PyObject* wrap_sum1(PyObject* self, PyObject* args) #调用了c语言的sum函数
{
int result;
int a=1;
int b=2;
if (! PyArg_ParseTuple(args, "ii", &a,&b)) #获取通过python传入的参数
return NULL;
printf("\n -- a=%d,b=%d \n",a,b);
result = sum(a,b);
return Py_BuildValue("i", result);
}
static PyMethodDef exampleMethods1[] =
{
{"sum1", wrap_sum1, METH_VARARGS, "Caculate N!"}, #这块要注意下,“sum1”的名字是在python中呈现的方法名;
{NULL, NULL}
};
void initexample1() #这块要注意下这个函数的命名就是init+Py_InitModule第一个参数名,如果不一致执行时会报错;
{
PyObject* m;
m = Py_InitModule("example1", exampleMethods1);
}
代码编写完毕后,
第二步:进行编译成功动态库--
gcc -fPIC example.c -o example1.so -shared -I/usr/include/python2.7 -I/usr/lib/python2.7/config
第三步:开始试验,注意要在动态库所在目录打开pyhon
[root@host150 callfunction_c]# python
Python 2.7.5 (default, Aug 4 2017, 00:39:18)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import example1
>>> import example1 as t
>>> t.sum(3,5)
-- a=3,b=5
8 # ----- 期望的结果;
>>>
练习2:python使用import ctypes方式调用c语言动态库的练习,
第一步:c语言动态库的制作,代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int sum(int a,int b)
{
return a+b;
}
第2步:编译:gcc -fPIC example2.c -o example2.so -shared
第3步:python开始调用动态库的实践:
>>> import ctypes
>>> loadso=ctypes.cdll.LoadLibrary
>>> cfunc=loadso("./example2.so")
>>> cfunc.sum(8,9)
17 #-- 期望的结果
>>>