我想malloc在 C 中放置一個函式。然后我想通過 Python 3.10 呼叫這個函式ctypes.DLL。那我就想free吧。
但是,我遇到了分段錯誤。這是我非常簡單的 C 代碼:
#include <stdlib.h>
struct QueueItem {
void *value;
struct QueueItem *next;
};
struct Queue {
struct QueueItem* head;
struct QueueItem* tail;
};
struct Queue * new_queue(void * value) {
struct Queue* queue = malloc(sizeof(struct Queue));
struct Queue queue_ = { value, NULL };
return queue;
}
void delete_queue(struct Queue* queue) {
free(queue);
};
我將使用gcc -fPIC -shared src/queue.c -o queue.so, 然后在 python 端編譯它:
import ctypes
queue = ctypes.CDLL("./queue.so")
q = ctypes.POINTER(queue.new_queue(1))
print(q)
print(type(q))
queue.delete_queue(q)
但是運行它會產生:
-1529189344
<class 'int'>
Segmentation fault
問題是,我如何在 C 中 malloc,通過 python 傳遞指標,然后在 C 中再次釋放它?.
參考的主要資源:
- 在 Python 中通過 Ctypes 將指標傳遞給 DLL
- Python Ctypes 將指標傳遞給包含空指標陣列的結構
- https://docs.python.org/3/library/ctypes.html
- 弄亂 ctypes.POINTER 但它抱怨型別,我不是這方面的專家。
uj5u.com熱心網友回復:
如果您沒有為函式定義restypeand ,則假定 the 是 C ( ),并且會根據您傳遞的內容猜測引數型別。這里的問題是C的隱式是(在 64 位系統上)指標寬度的一半,所以回傳的值只是指標的一半(完全沒用)。argtypesrestypeintc_intrestypeintnew_queue
為了安全和錯誤檢查,您應該在呼叫函式之前定義兩者,尤其是restype無法推斷的。
因此,對于您的代碼,您可能會這樣做:
import ctypes
queue = ctypes.CDLL("./queue.so")
queue.new_queue.argtypes = (c_void_p,)
queue.new_queue.restype = c_void_p
queue.delete_queue.argtypes = (c_void_p,)
queue.delete_queue.restype = None
q = queue.new_queue(1)
print(q)
print(type(q))
queue.delete_queue(q)
請注意,1作為引數傳遞給new_queue幾乎肯定是不正確的,但我懷疑它會在這里起作用,因為沒有代碼會實際嘗試使用它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/534168.html
標籤:PythonC指针类型
上一篇:如何列印鏈表中的所有節點?
下一篇:結構未初始化
