PYTHON和C的相互调用

python库和C语言是相互对应的,两者可以相互调用

PYTHON调用C/C++

PYTHON调用C

在这里插入图片描述

cftest.c

int cf_test()
{
	printf("hello python!\n");
	return 0;
}

cfcall.py

import ctypes
lib = ctypes.cdll.LoadLibrary
cflib = lib("./libcftest.so")
cflib.cf_test()

执行如下代码:
gcc -o libcftest.so -shared -fPIC cftest.c
python cfcall.py
最终输出:hello python!

PYTHON调用C++

将C++进行extern "c"进行声明即可;

PYTHON调用可执行程序

cexe.c

#include<stdio.h>
void hello(char *str)
{
	printf("hello %s\n",str);

}
int main(int argc ,char *argv[])
{
	if(argc==2)
	{
		hello(argv[1]);
	}
	else
	{
		printf("bye\n");
	}
	return 0;
}

cexecall.py

import os
main = "./cexe"
os.system(main + " python")

执行下面的代码
gcc cexe.c -o cexe
python cexecall.py
输出 hello python

C/C++扩展Python

Created with Raphaël 2.2.0 创建程序代码 包装代码 编译 执行代码

对于包装代码有四步

  1. 包含python.h文件
  2. 为每个函数增加PyObject *xx_func()的包装函数
  3. 为每个模块增加一个PyMethodDef xxMethods[]数组
  4. 增加模块初始化函数void initModule()
    对于编译代码
    创建编译代码的compile.py
from distutils.core import setup, Extension  
  
MOD = 'xx'  
setup(name=MOD, ext_modules=[Extension(MOD, sources=['xxx.c'])])  

创建应用程序

创建cpack.c

#include<stdio.h>
void python()
{
	printf("hello python\n");
}
void c()
{
	printf("hello c");
}

封装

对cpack.c里的函数进行封装
cpack.c

#include<stdio.h>
void python(void)
{
	printf("hello python\n");
}
void c(void)
{
	printf("hello c");
}

#include<Python.h>
static PyObject *cpack_python(PyObject *self ,PyObject *args)
{
	python();
	return (PyObject*)Py_BuildValue("");
}
static PyObject *cpack_c(PyObject *self ,PyObject *args)
{
	c();
	return (PyObject*)Py_BuildValue("");
}
static PyMethodDef cpackMethods[]=
{
	{"python",cpack_python,METH_VARARGS},
	{"c",cpack_c,METH_VARARGS},
	{NULL,NULL},
};
void initcpack(void)
{
	Py_InitModule("cpack",cpackMethods);
}

编译

compile.py

from distutils.core import setup, Extension
MOD = 'cpack'
setup(name=MOD, ext_modules=[Extension(MOD, sources=['cpack.c'])]) 
python2 compile.py build

编译完成后在./build/*lib/文件下

执行

像调用模块一下调用

C/C++调用PYTHON

Created with Raphaël 2.2.0 编写python文件 添加到C文件中 编译 执行

编写python文件c_add.py

def hello(str):
    print("hello " + str)

添加到c文件cpy.c

#include<Python.h>
int main()
{
	Py_Initialize();
	

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


	PyObject *pName = NULL;
	PyObject *pModule = NULL;
	PyObject *pDict = NULL;
	PyObject *pFunc = NULL;
	PyObject *pArgs = NULL;


	pName = PyString_FromString("c_add");
	pModule = PyImport_Import(pName);
	if(!pModule)
	{
		printf("failed\n");
		return -1;
	}
	pDict = PyModule_GetDict(pModule);
	pFunc = PyDict_GetItemString(pDict,"hello");
	pArgs = PyTuple_New(1);
	PyTuple_SetItem(pArgs,0,Py_BuildValue("s","python"));
	PyObject_CallObject(pFunc,pArgs);


	Py_DECREF(pName);
	Py_DECREF(pArgs);
	Py_DECREF(pModule);

	Py_Finalize();
}

编译
gcc -I/usr/include/python2.7 cpy.c -o cpy -L/usr/lib -lpython2.7
执行

猜你喜欢

转载自blog.csdn.net/limengjuhanxin/article/details/86527651