當前位置:首頁 » 編程語言 » cpythonh

cpythonh

發布時間: 2023-08-05 08:04:59

Ⅰ 目前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 即可

熱點內容
java三目表達式 發布:2025-02-06 23:58:41 瀏覽:740
android開啟wifi 發布:2025-02-06 23:50:08 瀏覽:495
騰訊雲伺服器是不是只有c盤 發布:2025-02-06 23:50:03 瀏覽:472
安卓如何選擇相冊 發布:2025-02-06 23:49:57 瀏覽:346
安卓究極風暴4在哪個軟體可以玩 發布:2025-02-06 23:49:10 瀏覽:8
如何調用伺服器的視頻 發布:2025-02-06 23:48:57 瀏覽:643
編程粉絲名 發布:2025-02-06 23:48:56 瀏覽:559
區域網存儲安裝 發布:2025-02-06 23:42:50 瀏覽:926
androidbug 發布:2025-02-06 23:31:56 瀏覽:51
php數字判斷 發布:2025-02-06 23:17:40 瀏覽:41