當前位置:首頁 » 編程語言 » pythonc調用

pythonc調用

發布時間: 2022-04-22 20:57:49

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

❷ 怎樣讓Python腳本與C++程序互相調用

二、Python調用C/C++

1、Python調用C動態鏈接庫

Python調用C庫比較簡單,不經過任何封裝打包成so,再使用python的ctypes調用即可。
(1)C語言文件:pycall.c

[html] view plain
/***gcc -o libpycall.so -shared -fPIC pycall.c*/
#include <stdio.h>
#include <stdlib.h>
int foo(int a, int b)
{
printf("you input %d and %d\n", a, b);
return a+b;
}
(2)gcc編譯生成動態庫libpycall.so:gcc -o libpycall.so -shared -fPIC pycall.c。使用g++編譯生成C動態庫的代碼中的函數或者方法時,需要使用extern "C"來進行編譯。
(3)Python調用動態庫的文件:pycall.py

[html] view plain
import ctypes
ll = ctypes.cdll.LoadLibrary
lib = ll("./libpycall.so")
lib.foo(1, 3)
print '***finish***'
(4)運行結果:

2、Python調用C++(類)動態鏈接庫

需要extern "C"來輔助,也就是說還是只能調用C函數,不能直接調用方法,但是能解析C++方法。不是用extern "C",構建後的動態鏈接庫沒有這些函數的符號表。
(1)C++類文件:pycallclass.cpp

[html] view plain
#include <iostream>
using namespace std;

class TestLib
{
public:
void display();
void display(int a);
};
void TestLib::display() {
cout<<"First display"<<endl;
}

void TestLib::display(int a) {
cout<<"Second display:"<<a<<endl;
}
extern "C" {
TestLib obj;
void display() {
obj.display();
}
void display_int() {
obj.display(2);
}
}
(2)g++編譯生成動態庫libpycall.so:g++ -o libpycallclass.so -shared -fPIC pycallclass.cpp。
(3)Python調用動態庫的文件:pycallclass.py

[html] view plain
import ctypes
so = ctypes.cdll.LoadLibrary
lib = so("./libpycallclass.so")
print 'display()'
lib.display()
print 'display(100)'
lib.display_int(100)
(4)運行結果:

3、Python調用C/C++可執行程序
(1)C/C++程序:main.cpp

[html] view plain
#include <iostream>
using namespace std;
int test()
{
int a = 10, b = 5;
return a+b;
}
int main()
{
cout<<"---begin---"<<endl;
int num = test();
cout<<"num="<<num<<endl;
cout<<"---end---"<<endl;
}
(2)編譯成二進制可執行文件:g++ -o testmain main.cpp。
(3)Python調用程序:main.py

[html] view plain
import commands
import os
main = "./testmain"
if os.path.exists(main):
rc, out = commands.getstatusoutput(main)
print 'rc = %d, \nout = %s' % (rc, out)

print '*'*10
f = os.popen(main)
data = f.readlines()
f.close()
print data

print '*'*10
os.system(main)
(4)運行結果:

4、擴展Python(C++為Python編寫擴展模塊)
所有能被整合或導入到其它python腳本的代碼,都可以被稱為擴展。可以用Python來寫擴展,也可以用C和C++之類的編譯型的語言來寫擴展。Python在設計之初就考慮到要讓模塊的導入機制足夠抽象。抽象到讓使用模塊的代碼無法了解到模塊的具體實現細節。Python的可擴展性具有的優點:方便為語言增加新功能、具有可定製性、代碼可以實現復用等。
為 Python 創建擴展需要三個主要的步驟:創建應用程序代碼、利用樣板來包裝代碼和編譯與測試。
(1)創建應用程序代碼

[html] view plain
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int fac(int n)
{
if (n < 2) return(1); /* 0! == 1! == 1 */
return (n)*fac(n-1); /* n! == n*(n-1)! */
}

char *reverse(char *s)
{
register char t, /* tmp */
*p = s, /* fwd */
*q = (s + (strlen(s) - 1)); /* bwd */

while (p < q) /* if p < q */
{
t = *p; /* swap & move ptrs */
*p++ = *q;
*q-- = t;
}
return(s);
}

int main()
{
char s[BUFSIZ];
printf("4! == %d\n", fac(4));
printf("8! == %d\n", fac(8));
printf("12! == %d\n", fac(12));
strcpy(s, "abcdef");
printf("reversing 'abcdef', we get '%s'\n", \
reverse(s));
strcpy(s, "madam");
printf("reversing 'madam', we get '%s'\n", \
reverse(s));
return 0;
}
上述代碼中有兩個函數,一個是遞歸求階乘的函數fac();另一個reverse()函數實現了一個簡單的字元串反轉演算法,其主要目的是修改傳入的字元串,使其內容完全反轉,但不需要申請內存後反著復制的方法。
(2)用樣板來包裝代碼
介面的代碼被稱為「樣板」代碼,它是應用程序代碼與Python解釋器之間進行交互所必不可少的一部分。樣板主要分為4步:a、包含Python的頭文件;b、為每個模塊的每一個函數增加一個型如PyObject* Mole_func()的包裝函數;c、為每個模塊增加一個型如PyMethodDef MoleMethods[]的數組;d、增加模塊初始化函數void initMole()。

❸ c如何調用python程序

C語言如何調用python,相關步驟如下:

首先,C語言中調用python,要使用頭文件Python.h。

2、接著,定義一個調用python的函數。

相關推薦:《Python教程》

3、函數中,設置python庫的路徑。

4、然後,初始化python。

5、運行一個python代碼,輸出How are you。

6、最後,釋放python。

❹ python怎麼調用c的main函數

if
__name__=="__main__":
print
'main'
當腳本作為執行腳本時__name__的值為__main__當腳本作為模塊時__name__為模塊文件名。舉個例子,a.py作為執行腳本時__name__的值是__main__。有2個腳本,a.py和b.py,a中引入b,執行a.py時,在b中模塊的__name__就是b.py

❺ c可以調用python嗎

可以的。

C中內嵌Python
新建立一個工程,首先需要將工作目錄設置到Python-3.1.1PCbuild中,以獲取到動態庫,至於靜態庫的包含,Include目錄的指定,那自然也是少不了的。文件中需要包含Python.h文件,這也是必須的。
介面中
Py_Initialize();
Py_Finalize();

其他的根據需求,再引入相應的python builder 即可

❻ python 怎麼調用c語言介面

ctypes: 可直接調用c語言動態鏈接庫。

使用步驟:

1> 編譯好自己的動態連接庫
2> 利用ctypes載入動態連接庫
3> 用ctype調用C函數介面時,需要將python變數類型做轉換後才能作為函數參數,轉換原則見下圖:

#Step1:test.c#include<stdio.h>

intadd(inta,intb)
{
returna+b;
}#Step2:編譯動態鏈接庫(如何編譯動態鏈接庫在本文不詳解,網上資料一大堆。)gcc-fPIC-sharedtest.c-olibtest.so
#Step3:test.py
fromctypesimport*mylib=CDLL("libtest.so")或者cdll.LoadLibrary("libtest.so")add=mylib.add
add.argtypes=[c_int,c_int]#參數類型,兩個int(c_int是ctypes類型,見上表)
add.restype=c_int#返回值類型,int(c_int是ctypes類型,見上表)
sum=add(3,6)

❼ 【python-C相互調用】python里的dict如何作為參數傳入.so中的c語言函數

#include<stdio.h>
#include<stdlib.h>
#include<Python.h>

staticPyObject*
wmf_reverse(PyObject*self,PyObject*args,PyObject*kwargs){
staticchar*kwlist[]={"name",NULL};
char*name=NULL;
PyObject*retval=NULL;

//問題1:只取一個字元串,format應該是"s"
//>>>if(PyArg_ParseTupleAndKeywords(args,keyds,"isi",kwlist,&name))
if(PyArg_ParseTupleAndKeywords(args,kwargs,"s",kwlist,&name)){
retval=(PyObject*)Py_BuildValue("i",1);
printf("%s ",name);
//問題2:不要釋放
//>>>free(name);
}else{
retval=(PyObject*)Py_BuildValue("i",0);
}
returnretval;
}

staticPyMethodDef
wmf_methods[]={
{"reverse",(PyCFunction)wmf_reverse,METH_VARARGS|METH_KEYWORDS,"reverse"},
//問題3:方法定義表,應該用一條空記錄來表示結束。
{NULL,NULL,0,NULL},
};

//問題4:沒有定義mole
staticstructPyMoleDef
wmf_mole={
PyMoleDef_HEAD_INIT,
"wmf",/*nameofmole*/
NULL,/*moledocumentation,maybeNULL*/
-1,/*sizeofper-interpreterstateofthemole,
or-.*/
wmf_methods,
};

//問題5:入口函數要聲明為:PyMODINIT_FUNC
PyMODINIT_FUNC
PyInit_wmf(void){
//問題6:Py_InitMole要初始化的是模塊,不是方法。所以傳方法定義是錯誤的。
//另外,python2.x是用Py_Init_mole,python3.x改用PyMole_Create了。
//兩者略有差別,自己注意一下吧。這里我用的是python3.x。
//Py_InitMole("wmf",ExtestMethods);
PyObject*m;
m=PyMole_Create(&wmf_mole);
if(m==NULL){
returnNULL;
}
returnm;
}

❽ 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

❾ 如何讓python調用C和C++代碼

二、Python調用C/C++1、Python調用C動態鏈接庫Python調用C庫比較簡單,不經過任何封裝打包成so,再使用python的ctypes調用即可。(1)C語言文件:pycall.c[html]viewplain/***gcc-olibpycall.so-shared-fPICpycall.c*/#include#includeintfoo(inta,intb){printf("youinput%dand%d\n",a,b);returna+b;}(2)gcc編譯生成動態庫libpycall.so:gcc-olibpycall.so-shared-fPICpycall.c。使用g++編譯生成C動態庫的代碼中的函數或者方法時,需要使用extern"C"來進行編譯。(3)Python調用動態庫的文件:pycall.py[html]viewplainimportctypesll=ctypes.cdll.LoadLibrarylib=ll("./libpycall.so")lib.foo(1,3)print'***finish***'(4)運行結果:2、Python調用C++(類)動態鏈接庫需要extern"C"來輔助,也就是說還是只能調用C函數,不能直接調用方法,但是能解析C++方法。不是用extern"C",構建後的動態鏈接庫沒有這些函數的符號表。(1)C++類文件:pycallclass.cpp[html]viewplain#includeusingnamespacestd;classTestLib{public:voiddisplay();voiddisplay(inta);};voidTestLib::display(){cout#include#includeintfac(intn){if(n<2)return(1);/*0!==1!==1*/return(n)*fac(n-1);/*n!==n*(n-1)!*/}char*reverse(char*s){registerchart,/*tmp*/*p=s,/*fwd*/*q=(s+(strlen(s)-1));/*bwd*/while(p

❿ python調用c語言編譯器

如何讓python調用C和C++代碼

安裝python後,會有一個chm格式的python手冊。要搞明白如何讓python調用C/C++代碼(也就是寫python的 extension),你需要征服手冊中的
<<Extending && embedding>>厚厚的一章。在昨天花了一個小時看地頭暈腦脹,仍然不知道如何寫python的extension後,查閱了一些其他 書籍,最終在<<Python Programming On Win32>>書中找到了教程。
下面記錄一下如何在visual studio 2005中,寫一段C/C++的MessageBox代碼,然後提供後python調用,最後的結果當然是顯示一個MessageBox.
1. 首先要明白的是,所謂的python擴展(也就是你提供給python的c/c++代碼,不一定是c/c++代碼,可以是其他語言寫的代碼)是一個 dll,並且這個dll放在本機python安裝目錄下的DLLs目錄下(譬如我機器上的路徑是:F:\Program Files\Python25\DLLs),假如我們接下來要寫的擴展mole名為mb,python調用的代碼為: import mb
mb.showMsg("Python's really amazing, I kindda love it!")
python怎麼找到我們的mb模塊呢?就是上面說的,我們要生成一個mb.dll,然後拷貝到Dlls目錄下面,為了區別普通的dll和python專用擴展的dll,我們的 mb.dll修改成mb.pyd(python dll)
2. 搭建環境,我們要使用python提供的c頭文件和lib庫來進行擴展的開發。 在vs 2005下點擊菜單 "工具"->"選項", 打開選項對話框,選擇"項目和解決方案->VC++目錄", 然後在右邊"顯示以下內容的目錄"得comboBox上選擇"包含文件」,添加python的include目錄(我的機器上是"F:\Program
Files\Python25\include"),然後選擇庫文件,添加python的libs目錄(我的機器上是"F:\Program Files\Python25\libs")。
既然擴展是一個dll,接下來我們要建立一個「動態鏈接庫」工程,然後開始寫代碼:
#include <python.h> //python.h是包含python一些定義的頭文件,在python的include目錄下 /*
我的python版本是2.5, 因為安裝python後它沒提供debug下的lib庫文件,因此你必須生成release版的dll,
想要生成dll版本的,你要到python官網上自己去下載python源代碼,當然你可以繼續生成release版本的dll,但dll中包含調試信息

熱點內容
個人網站模板源碼 發布:2025-05-18 02:51:17 瀏覽:489
主伺服器ip地址 發布:2025-05-18 02:46:29 瀏覽:854
電腦配置太低玩不了絕地求生怎麼辦 發布:2025-05-18 02:38:39 瀏覽:796
存儲過程怎麼出錯了 發布:2025-05-18 02:37:16 瀏覽:367
32寸演算法 發布:2025-05-18 02:22:14 瀏覽:743
寶塔資料庫備份 發布:2025-05-18 02:14:18 瀏覽:192
安卓商店下載的光遇是什麼服 發布:2025-05-18 02:13:38 瀏覽:31
網頁挖礦源碼 發布:2025-05-18 02:13:34 瀏覽:307
centosftp伺服器設置參數 發布:2025-05-18 02:12:55 瀏覽:216
賬號密碼保存在瀏覽器哪裡 發布:2025-05-18 01:56:43 瀏覽:833