接下來將簡單介紹python如何呼叫c和c++。包括呼叫整型,陣列等情況。
c函式返回整型int
c** test.c
#include #include int func(int a, int b)
編譯成so包
gcc -o testpycll_64.so -shared -fpic test.c
python**
import ctypes
import platform
ll = ctypes.cdll.loadlibrary
lib = ll(
"./testpycll_64.so"
)lib.func(1,
3)# platform.architecture()
執行之後的結果:
這裡有乙個問題,我是在jupyter notebook下的,只顯示了c函式的返回值,對於過程列印語句並沒有輸出。但在命令列下是可以輸出的,如下所示:
mypy.py 是python檔名。
c函式返回整型陣列 int
c**:
#include #include int* func(int a, int b)
python **:需要用到numpy包(這裡原先一直返回失敗,也是試了非常多的方法才解決)
import ctypes
import platform
from numpy.ctypeslib import ndpointer
ll = ctypes.cdll.loadlibrary
lib = ll(
"./testpycll_64.so"
)lib.func.restype = ndpointer(dtype=ctypes.c_int, shape=(3
,))res = lib.func(1,
3)print
(res)
執行之後的結果:
c函式傳入整型陣列 int
c**
#include #include int func(int a, int n)
c++ **
#include #include using namespace std;
class testclass
;char* testclass::func()
extern "c"
}
生成so包指令:注意變成g++
g++ -o testpycll_64.so -shared -fpic test.cpp
python**
import ctypes
import platform
from numpy.ctypeslib import ndpointer
import numpy as np
ll = ctypes.cdll.loadlibrary;
lib = ll(
"./testpycll_64.so");
lib.myfunc1.restype = ctypes.c_uint64;
res = lib.myfunc1();
res = ctypes.string_at(res)
;print
(res)
;
執行結果:
以上大致是python呼叫c/c++的方法,有不足之處還望大家指出。
python 呼叫 C C 程式設計
p1 首先,先用c寫乙個簡單的函式 show.c include void showstring 這個函式是乙個最簡單的helloworld函式,幾乎所有程式語言教材都會以她作為第乙個例子 跑題了。我們需要做的是在乙個python指令碼中呼叫這個函式 show.py usr bin env pyth...
Python呼叫c c 函式(1)
python開發效率高,執行效率低。而c c 恰恰相反。因此在python指令碼中呼叫c c 的庫,對python進行擴充套件,是很有必要的。使用python api,需要安裝python dev。test.cpp檔案如下 include 6 python.h 包含python的標頭檔案 1 c c...
C C 呼叫python(新手必看)
目錄 1.背景介紹與程式設計環境 2.完整例項演示 3.問題集錦 4.總結 5.參考鏈結 背景介紹 近年來,python語言憑藉著自身語言的簡單易學 相對於其他程式語言來說 及其功能強大的函式庫 還有其他優點 受到許多程式設計愛好者的青睞,同時十分廣泛的用於人工智慧演算法程式設計中。c c 語言是基...