编译环境:

   Mac、Python2.7



一、 Python 调用C:

   1、准备.c , .h文件:pcallc.c 、pcallc.h

#include <stdio.h>
#include "pcallc.h"
int hello(int a)
{
	printf("hello world!\n");
	return a;
}
#ifndef PCALLC_H
#define PCALLC_H

int hello();
#endif

2、使用命令:gcc -o pcallc.so -shared -fPIC pcallc.c.  生成动态库pcallc.so

3、编写.py文件: pcallc.py

#-*- coding:utf-8 -*-
import ctypes

l1=ctypes.cdll.LoadLibrary
lib=l1("./pcallc.so")
lib.hello(3)
# print a 
print '****finsh****'


4、去到文件目录,使用python命令运行.py 程序

    得到结果:

      

c   库和python库 c 调用python库_python

5、撒花花~



二、 C 调用Python:

    1、准备.py文件:ccallp.py  

#-*- coding:utf-8 -*-
#某一天看到有人发现了一个非常强大的函数
def great_function(a):
	return a+1

   

2、编写.h 文件: ccallp.h

#ifndef CCALLP_H
#define CCALLP_H

#include "....(python2.7安装路径)/include/python2.7/Python.h" 
//Python.h 文件所在路径在你的python2.7 安装目录下的include/python2.7/ 下面。 
// 不知道路径的,可以直接命令:find  / -name Python.h查看,然后复制到include “..” 里面 (我的输入这命令,出来一大堆东西,但还是可以容易找出自己的安装路径)
 int great_function_from_python(int a);
#endif

    3、编写.c文件(重点):ccallp.c

#include "ccallp.h"
#include <stdio.h>
#include <stdlib.h>

int great_function_from_python(int a)
{
	Py_Initialize();

	 // 检查初始化是否成功  
    // if ( !Py_IsInitialized() ) {  
    // 	printf("error!");
    //     return -1;  
    // }  

	int res;
	PyObject *pModule,*pFunc;
	PyObject *pArgs, *pValue;

	PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('./')");

	/*import ccallp.py file 注意没有.py*/
	pModule = PyImport_Import(PyString_FromString("ccallp"));

	if ( !pModule ) {  
        printf("can't find ccallp.py");  
        getchar();  
        return -1;  
    }  

	/* great_module.great_function */
	pFunc = PyObject_GetAttrString(pModule,"great_function");

	/* build args */
	pArgs = PyTuple_New(1);
	PyTuple_SetItem(pArgs,0,PyInt_FromLong(a));

	/*call*/
	pValue = PyObject_CallObject(pFunc,pArgs);

	res = PyInt_AsLong(pValue);

	Py_Finalize();

	return res;

}

/*也可以直接执行以下命令  反注释main 函数 直接运行这个文件
    : gcc ccallp.c -o ccallp -I/usr/include/python2.7/ -lpython2.7
    :  ./ccallp 
*/

 // int main(int argc, char *argv[])
// {

// 	printf("%d\n",great_function_from_python(4));

// }

    4、编写main文件:ccallpMain.c

#include "ccallp.h"
#include <stdio.h>
#include <stdlib.h>

// 执行命令:gcc ccallp.c ccallpMain.c -o ccallpMain -I/usr/include/python2.7/ -lpython2.7
//  ./ccallpMain

int main(int argc, char *argv[])
{
	printf("%d\n",great_function_from_python(3));

}

    5、执行命令:

    gcc ccallp.c ccallpMain.c -o ccallpMain -I/usr/include/python2.7/ -lpython2.7    

    ./ccallpMain

    得出最后结果:

    

c   库和python库 c 调用python库_#include_02

    6、本文只使用了简单的例子陈列出C和Python相互调用的过程,了解更多可参考:猛戳!

    7、收花 *_*  ~  喋喋

    --绝望之后,生命的一切都是意外之喜(世间再无霍金)