[英]call C code from Python via ctypes, use python object list
[英]Modifying python list within C code and returning modified list back to python code via ctypes
我無法通過 ctypes 庫將 C 代碼與 python 結合起來。 我正在嘗試將 python 列表傳遞到 C function 列表中,該列表迭代列表並修改其值。 我現在想在我的 python 代碼中使用修改后的列表。
C 代碼 - 迭代器。c
#include <math.h>
void apply_cosine(double *array,int length)
{
for(int i = 0 ; i < length; i++){
array[i] = cos(array[i]);
}
}
Python 代碼 - python_base.py
import os
import ctypes
current_dir = os.getcwd()
full_path = current_dir + "/lib.so"
_lib = ctypes.CDLL(full_path)
_lib.apply_cosine.argtypes = (ctypes.POINTER(ctypes.c_double), ctypes.c_int)
# _lib.apply_cosine.restype = ctypes.c_double
def apply_cosine(array: list) -> list:
'''Wrapper function to apply cosine function to each element in the list.
'''
length = len(array)
array_type = ctypes.c_double * length
array = _lib.apply_cosine(array_type(*array), ctypes.c_int(length))
return array
if __name__ == "__main__":
test = [12., 44., 23., 32., 244., 23.]
print(apply_cosine(test))
我很確定我的問題是返回類型。 我的 c 代碼僅通過指針修改列表,並沒有顯式返回列表。 因此,在 c 代碼修改列表中似乎沒有傳遞回 python 代碼。
您對如何正確執行此操作有任何建議嗎?
非常感謝您的幫助。
為了將來參考,該代碼適用於@Marat 和@SamMason 的建議:
C 代碼 - 迭代器。c
#include <math.h>
void apply_cosine(double *array,int length)
{
for(int i = 0 ; i < length; i++){
array[i] = cos(array[i]);
}
}
Python 代碼 - python_base.py
-> 構建共享庫,使用命令:gcc -fPIC -shared -o lib.so iterator.c
import os
import ctypes
current_dir = os.getcwd()
full_path = current_dir + "/lib.so"
_lib = ctypes.CDLL(full_path)
_lib.apply_cosine.argtypes = (ctypes.POINTER(ctypes.c_double), ctypes.c_int)
def apply_cosine(array: list) -> list:
'''Wrapper function to apply cosine function to each element in the list.
'''
length = len(array)
array = (ctypes.c_double * length)(*array)
_lib.apply_cosine(array, length)
return list(array)
if __name__ == "__main__":
test = [12., 44., 23., 32., 244., 23.]
test = apply_cosine(test)
print(test)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.