正如標題所說,在過去的 48 小時里,我一直在嘗試將向量從 python 專案傳遞給我撰寫的一組 C 函式。最終我得出結論,根據對這里過去帖子的一些閱讀,使用陣列而不是向量可能更容易。這導致我在下面嘗試本教程,但它最初只是為了舉例說明傳入一個整數并回傳它。我嘗試更改代碼,以便它通過參考來自 python 的 3 個數字長串列/陣列來傳遞,然后將 1 添加到其中的每個數字。但是,當我運行它時,我可以看到它獲取陣列沒有問題并列印在 c 函式中修改的值,但它沒有修改原始 python 變數。事實上,我得到的是“<class ' main.c_double_Array_3'>" 當我嘗試列印包裝函式的輸出時回傳。下面是我到目前為止嘗試過的代碼(在當前狀態下)。如果有人可以提供有關資源的一些指導,以獲得關于如何要做到這一點,或者一些關于做什么的幫助,我將不勝感激。
Simple_calculations C 檔案
extern "C" void our_function(double * numbers) {
numbers[0] = 1;
numbers[1] = 1;
numbers[2] = 1;
std::cout << numbers[0] << std::endl;
std::cout << numbers[1] << std::endl;
std::cout << numbers[2] << std::endl;
}
Python 檔案
import os
import ctypes
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
os.system('g -dynamiclib -shared -o simple_calculations.dylib simple_calculations.cpp -std=c 17')
_sum = ctypes.CDLL('simple_calculations.dylib')
_sum.our_function.argtypes = (ctypes.POINTER(ctypes.c_double),)
def our_function(numbers):
array_type = ctypes.c_double * 3
_sum.our_function(array_type(*numbers))
return array_type
z = our_function([0, 1, 2])
print(z)
輸出
1
2
3
<class '__main__.c_double_Array_3'>
uj5u.com熱心網友回復:
你回來了array_type。那是一個型別,而不是型別的一個實體。該實體是您array_type(*numbers)傳遞給函式的,但它不會被保留。將其分配給一個變數并回傳that,或者更好地將其轉換回 Python 串列,如下所示:
測驗.cpp
#ifdef _WIN32
# define API __declspec(dllexport)
#else
# define API
#endif
extern "C" API void our_function(double * numbers) {
numbers[0] = 1;
numbers[1] = 1;
numbers[2] = 1;
}
測驗.py
import ctypes
_sum = ctypes.CDLL('./test')
_sum.our_function.argtypes = ctypes.POINTER(ctypes.c_double),
def our_function(numbers):
array_type = ctypes.c_double * 3 # equiv. to C double[3] type
arr = array_type(*numbers) # equiv. to double arr[3] = {...} instance
_sum.our_function(arr) # pointer to array passed to function and modified
return list(arr) # extract Python floats from ctypes-wrapped array
z = our_function([0, 1, 2])
print(z)
輸出:
[1.0, 2.0, 3.0]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/456706.html
