[英]Python Bindings with C++
我有興趣在 C++ 中編寫函數,以后可以在 Python 中“導入”。 例如,我在 C++ 中寫了一個簡單的 function ,它添加了兩個整數:
//function declaration
int addition(int a,int b);
//function definition
int addition(int a,int b)
{
return (a+b);
}
我還有一個 header 文件,其中包含:
extern "C" MATHLIBRARY_API int addition(int a, int b);
然后在 Python 中,由於ctypes
的幫助,代碼很簡單:
import ctypes
path = "C:\\my path to the .dll file"
# load the library
lib = ctypes.CDLL('{0}\MathLibrary.dll'.format(path))
answer = lib.addition(14, 2)
print(answer) // OUTPUT: 16
到目前為止一切都很好,但我想用更復雜的數據結構做一些數學運算,比如vectors
。 我想要一個元素向量(例如: {12, 10, 2, 14}
)並為向量內的所有元素添加一個數字。 例如, n = 2, vector = {12, 10, 2, 14}, output = {14, 12, 4, 16}
。 我寫了一個在 C++ 中工作的 function,但我無法綁定到 Python。 我相信這是因為我正在使用vectors
以及 header 文件中的extern "C"
。
ctypes 只允許您與使用 C 類型的庫進行交互,而不是 C++。 boost.python、pybind11 等允許您傳遞 C++ 對象。
但是,有一種方法可以使用 C 風格的 arrays 在 ctypes 中執行您想要執行的操作。
像這樣聲明一個 function:
extern "C" MATHLIBRARY_API void addToArray(int *array, int num, int size);
並像這樣定義它:
void addToArray(int *array, int num, int size)
{
for (int i=0; i < size; ++i)
{
array[i] = array[i] + num;
}
}
然后在您的 Python 腳本中執行以下操作:
nums = [12, 10, 2, 14]
array_type = ctypes.c_int * len(nums)
lib.additionArray.argtypes = [ctypes.POINTER(ctypes.c_int), ctypes.c_int, ctypes.c_int]
array = array_type(*nums)
lib.addToArray(array, ctypes.c_int(2), ctypes.c_int(len(nums)))
# copy modified array into original list
nums[:] = list(array)
print(nums)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.