cpythonh
Ⅰ 目前cpython调用C/C++的主流手段是cython么
还可以使用Cython来实现混编
1 下载Cython,用Python setup.py install进行安装
2 一个实例
① 创建helloworld目录创建helloworld.pyx,内容如下:cdef extern from"stdio.h": extern int printf(const char *format, ...) def SayHello(): printf("hello,world\n")
② 编译,最方便的是利用python的Distutils了,
helloworld目录下创建Setup.py,内容如下:from distutils.core import setupfrom distutils.extension import Extensionfrom Cython.Build import cythonize setup( name = 'helloworld', ext_moles=cythonize([ Extension("helloworld", ["helloworld.pyx"]), ]),) 编译:python Setup.py build安装:python Setup.py install安装后,会将在build/lib.???目录下生成的helloworld.pyd拷贝到Lib/site-packages注: 有时我们只是希望测试一下,并不希望安装,这时可以把build/lib.???目录下的helloworld.pyd拷贝到当前目录 或者在importhelloworld前执行脚本:import sys;sys.path.append(pathof helloworld.pyd) ③ 测试:>>>import helloworld >>>helloworld.SayHello() hello,world
Ⅱ python调用c函数
Python是解释性语言, 底层就是用c实现的, 所以用python调用C是很容易的, 下面就总结一下各种调用的方法, 给出例子, 所有例子都在ubuntu9.10, python2.6下试过
1. Python 调用 C (base)
想在python中调用c函数, 如这儿的fact
#include <Python.h>
int fact(int n)
{
if (n <= 1)
return 1;
else
return n * fact(n - 1);
}
PyObject* wrap_fact(PyObject* self, PyObject* args)
{
int n, result;
if (! PyArg_ParseTuple(args, "i:fact", &n))
return NULL;
result = fact(n);
return Py_BuildValue("i", result);
}
static PyMethodDef exampleMethods[] =
{
{"fact", wrap_fact, METH_VARARGS, "Caculate N!"},
{NULL, NULL}
};
void initexample()
{
PyObject* m;
m = Py_InitMole("example", exampleMethods);
}
把这段代码存为wrapper.c, 编成so库,
gcc -fPIC wrapper.c -o example.so -shared -I/usr/include/python2.6 -I/usr/lib/python2.6/config
然后在有此so库的目录, 进入python, 可以如下使用
import example
example.fact(4)
2. Python 调用 C++ (base)
在python中调用C++类成员函数, 如下调用TestFact类中的fact函数,
#include <Python.h>
class TestFact{
public:
TestFact(){};
~TestFact(){};
int fact(int n);
};
int TestFact::fact(int n)
{
if (n <= 1)
return 1;
else
return n * (n - 1);
}
int fact(int n)
{
TestFact t;
return t.fact(n);
}
PyObject* wrap_fact(PyObject* self, PyObject* args)
{
int n, result;
if (! PyArg_ParseTuple(args, "i:fact", &n))
return NULL;
result = fact(n);
return Py_BuildValue("i", result);
}
static PyMethodDef exampleMethods[] =
{
{"fact", wrap_fact, METH_VARARGS, "Caculate N!"},
{NULL, NULL}
};
extern "C" //不加会导致找不到initexample
void initexample()
{
PyObject* m;
m = Py_InitMole("example", exampleMethods);
}
把这段代码存为wrapper.cpp, 编成so库,
g++ -fPIC wrapper.cpp -o example.so -shared -I/usr/include/python2.6 -I/usr/lib/python2.6/config
然后在有此so库的目录, 进入python, 可以如下使用
import example
example.fact(4)
3. Python 调用 C++ (Boost.Python)
Boost库是非常强大的库, 其中的python库可以用来封装c++被python调用, 功能比较强大, 不但可以封装函数还能封装类, 类成员.
http://dev.gameres.com/Program/Abstract/Building%20Hybrid%20Systems%20with%20Boost_Python.CHN.by.JERRY.htm
首先在ubuntu下安装boost.python, apt-get install libboost-python-dev
#include <boost/python.hpp>
char const* greet()
{
return "hello, world";
}
BOOST_PYTHON_MODULE(hello)
{
using namespace boost::python;
def("greet", greet);
}
把代码存为hello.cpp, 编译成so库
g++ hello.cpp -o hello.so -shared -I/usr/include/python2.5 -I/usr/lib/python2.5/config -lboost_python-gcc42-mt-1_34_1
此处python路径设为你的python路径, 并且必须加-lboost_python-gcc42-mt-1_34_1, 这个库名不一定是这个, 去/user/lib查
然后在有此so库的目录, 进入python, 可以如下使用
>>> import hello
>>> hello.greet()
'hello, world'
4. python 调用 c++ (ctypes)
ctypes is an advanced ffi (Foreign Function Interface) package for Python 2.3 and higher. In Python 2.5 it is already included.
ctypes allows to call functions in dlls/shared libraries and has extensive facilities to create, access and manipulate simple and complicated C data types in Python - in other words: wrap libraries in pure Python. It is even possible to implement C callback functions in pure Python.
http://python.net/crew/theller/ctypes/
#include <Python.h>
class TestFact{
public:
TestFact(){};
~TestFact(){};
int fact(int n);
};
int TestFact::fact(int n)
{
if (n <= 1)
return 1;
else
return n * (n - 1);
}
extern "C"
int fact(int n)
{
TestFact t;
return t.fact(n);
}
将代码存为wrapper.cpp不用写python接口封装, 直接编译成so库,
g++ -fPIC wrapper.cpp -o example.so -shared -I/usr/include/python2.6 -I/usr/lib/python2.6/config
进入python, 可以如下使用
>>> import ctypes
>>> pdll = ctypes.CDLL('/home/ubuntu/tmp/example.so')
>>> pdll.fact(4)
12
Ⅲ linux下,C插入Python,就在include <python.h>上卡住了
拿出一个例子来分析一下,不就是总结吗?
#include <Python.h>
char* python_code1 = "\
import wx\n\
f = wx.Frame(None, -1, 'Hello from wxPython!', size=(250, 150))\n\
f.Show()\n\
";
PyRun_SimpleString(python_code1);
char* python_code2 = "\
import sys\n\
sys.path.append('.')\n\
import embedded_sample\n\
\n\
def makeWindow(parent):\n\
win = embedded_sample.MyPanel(parent)\n\
return win\n\
";
PyObject* globals = PyDict_New();
PyObject* builtins = PyImport_ImportMole("__builtin__");
PyDict_SetItemString(globals, "__builtins__", builtins);
Py_DECREF(builtins);
// Execute the code to make the makeWindow function
result = PyRun_String(python_code2, Py_file_input, globals, globals);
// Was there an exception?
if (! result) {
PyErr_Print();
wxPyEndBlockThreads(blocked);
return NULL;
}
Py_DECREF(result);
// Now there should be an object named 'makeWindow' in the dictionary that
// we can grab a pointer to:
PyObject* func = PyDict_GetItemString(globals, "makeWindow");
Ⅳ 求助 关于c程序中嵌入Python的问题
嵌入
与python的扩展相对,嵌入是把Python解释器包装到C的程序中。这样做可以给大型的,单一的,要求严格的,私有的并且(或者)极其重要的应用程序内嵌Python解释器的能力。一旦内嵌了Python,世界完全不一样了。
C调用python中的函数:
hw.py:
#coding=utf8
def hw_hs(canshu):
return canshu
if __name__ == "__main__":
ccss = "I am hw"
print hw_hs(ccss)
helloWorld.py:
#coding=utf8
import hw
def hello():
ccss = "I am helloWorld"
return hw.hw_hs(ccss)
if __name__ == "__main__":
print hello()
testcpypy.c:
//#include "testcpypy.h"
#include <Python.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
//初始化Python
Py_Initialize();
if (!Py_IsInitialized()) {
printf("Py_Initialize");
getchar();
return -1;
}
//执行python语句
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
PyObject *pMole = NULL;
PyObject *pFunc = NULL;
PyObject *reslt =NULL;
//载入python模块
if(!(pMole = PyImport_ImportMole("helloWorld"))) {
printf("PyImport_ImportMole");
getchar();
return -1;
}
//查找函数
pFunc = PyObject_GetAttrString(pMole, "hello");
if ( !pFunc || !PyCallable_Check(pFunc) )
{
printf("can't find function [hello]");
getchar();
return -1;
}
//调用python中的函数
reslt = (PyObject*)PyEval_CallObject(pFunc, NULL);
//printf("function return value : %d\r\n", PyInt_AsLong(reslt));
//将python返回的对象转换为C的字符串
char *resltc=NULL;
int res;
res = PyArg_Parse(reslt, "s", &resltc);
if (!res) {
printf("PyArg_Parse");
getchar();
return -1;
}
printf("resltc is %s", resltc);
getchar();
//释放内存
Py_DECREF(reslt);
Py_DECREF(pFunc);
Py_DECREF(pMole);
//关闭python
Py_Finalize();
return 0;
}
编译:
gcc -o testcpypy testcpypy.c -IC:\Python27\include -LC:\Python27\libs -lpython27 ---C:\Python27为python安装目录
或:
gcc -c testcpypy.c -IC:\Python27\include
gcc -o testcpypy.exe testcpypy.o -LC:\Python27\libs -lpython27
执行结果:
带参数的情况:
#include "callpydll.h"
#include "Python.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
int callhello(char *instr, char *outstr)
{
PyObject *pMole = NULL;
PyObject *pFunc = NULL;
PyObject *reslt = NULL;
PyObject *pParm = NULL;
char *resltc = NULL;
int resltn;
int res;
char *helloWorld = "TestIM_ProtocBuf";
char *im_account = "aaaa";
char *auth_code = "aaaa";
char *im_uid = "aaaa";
char *proxy_topic = "";
//初始化Python
Py_Initialize();
if (!Py_IsInitialized()) {
printf("Py_Initialize");
getchar();
return -1;
}
//执行python语句
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
//载入python模块
if(!(pMole = PyImport_ImportMole(helloWorld))) {
printf("PyImport_ImportMole");
getchar();
return -2;
}
//查找函数
pFunc = PyObject_GetAttrString(pMole, "login_proxy_body_serialize");
if ( !pFunc || !PyCallable_Check(pFunc) )
{
printf("can't find function [hello]");
getchar();
return -3;
}
//参数转换C --> python, 参数必须是元组(一个参数也是,否则会失败!!!坑啊)
pParm = Py_BuildValue("(ssss)", im_account, auth_code, im_uid, proxy_topic);
//调用python中的函数
reslt = (PyObject*)PyEval_CallObject(pFunc, pParm);
//将python返回的对象转换为C的字符串
res = PyArg_ParseTuple(reslt, "si", &resltc, &resltn);
if (!res) {
printf("PyArg_Parse");
getchar();
return -4;
}
printf("resltn is %d", resltn);
memcpy(outstr, resltc, strlen(resltc)+1);
//释放内存
Py_DECREF(reslt);
Py_DECREF(pFunc);
Py_DECREF(pMole);
Py_DECREF(pParm);
//关闭python
Py_Finalize();
return 0;
}
int main() {
int i;
char *dais = "iammain";
char res[10240];
memset(res,'\0',sizeof(res));
i = callhello(dais, res);
if(0 != i) {
printf("Notify:error");
getchar();
return -1;
}
printf("result is %s", res);
getchar();
return 0;
}
Ⅳ C语言程序如何调用python程序
下面是一个例子:
首先是python的一个简单函数
class Hello:
def __init__(self, x):
self.a = x
def print(self, x=None):
print(x)
def xprint():
print("hello world")
if __name__ == "__main__":
xprint()
h = Hello(5)
h.print()1
下面是C语言
#include <python3.4m/Python.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
Py_Initialize();
// 将当前目录加入sys.path
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
// 导入hello.py模块
PyObject *pmole = PyImport_ImportMole("hello");
// 获得函数xprint对象,并调用,输出“hello world\n”
PyObject *pfunc = PyObject_GetAttrString(pmole, "xprint");
PyObject_CallFunction(pfunc, NULL);
// 获得类Hello并生成实例pinstance,并调用print成员函数,输出“5 6\n”
PyObject *pclass = PyObject_GetAttrString(pmole, "Hello");
PyObject *arg = Py_BuildValue("(i)", 5);
PyObject *pinstance = PyObject_Call(pclass, arg, NULL);
PyObject_CallMethod(pinstance, "print", "i", 6);
Py_Finalize();
return 0;
}
编译命令如下:
gcc pyapi.c -lpython3.4m -o pyapi
Ⅵ C语言怎么转化成python
score={'a':5,'b':4,'c':3,'d':2,'e':1}
N=40
sum=0
foriinrange(N):
answer=raw_input("请输入你第%d题的选择(a-e):"%(i+1))
answer=answer.lower()
whileanswernotinscore:
answer=raw_input("请输入正确的选项!:")
answer=answer.lower()
sum+=score[answer]
print("你的总分为%d"%sum)
ifsum>=168:
print("A")
elif136<sum<168:
print("B")
elif104<sum<=136:
print("C")
elif72<sum<=104:
print("D")
else:
print("E")
这个python 程序肯定 和上面的C结果不一样
else if (136<sum<168) 在C中肯定为真,所以上面的C程序只会打印 A或者 B,CDE任何情况下都不会打印 ,Pytyhon会完全打印
直接说出程序要求
Ⅶ 为什么python可以调用C或者C++写的模块
Python的API(应用程序编程接口)定义了一系列的函数、宏指令和变量 来与Python的运行系统的大部分方面进行连接通信,而通常来说,用C语言编写的Python API 会在程序文档里添加“python.h”作为头文件。
按我的理解来说就像Python把一个值交给运行系统,然后运行系统把这个值转化成C语言能够识别的值,然后交到C语言模块去做运算,运算好了把结果值交给Python的运行系统,处理成Python能够识别的值。
你不妨看看这几个网页:
http://hi..com/softguarder/blog/item/c3dc8b02b44cec80d43f7c57.html
http://docs.python.org/extending/extending.html#a-simple-example
http://hi..com/softguarder/blog/item/c3dc8b02b44cec80d43f7c57.html
Ⅷ c可以调用python吗
可以的。
C中内嵌Python
新建立一个工程,首先需要将工作目录设置到Python-3.1.1PCbuild中,以获取到动态库,至于静态库的包含,Include目录的指定,那自然也是少不了的。文件中需要包含Python.h文件,这也是必须的。
接口中
Py_Initialize();
Py_Finalize();
其他的根据需求,再引入相应的python builder 即可