Re: [問題] 關於ctypes structure之使用
※ 引述《takebreak (怨念)》之銘言:
: 各位先進好,想請教各位一個問題;
: 小弟撰寫一個DLL檔, 結合其它函式庫,
: 包裹準備要在python中使用的函式,
: 然而在使用structure交換資料時出現了問題,
: 我想達到的目的是將結構傳入函式中處理,
: 由函式將值寫入結構的記憶體位置達到目的;
: python:
: -----------------------------------
: #宣告結構struct
: class point(Structure):
: _fields_ = [("x", c_int),
: ("y", c_int)]
: #宣告target由20個point組成
: target = point*20
: -----------------------------------
: dll 實作函式:
: -----------------------------------
: DLLEXPORT void test_fuc(struct point *b)
: {
: b->x = 1;
: b->y = 2;
: }
: ----------------------------------
: python呼叫:
: -----------------------------------
: from ctypes import *
: class point(Structure):
: _fields_ = [("x", c_int),
: ("y", c_int)]
: x = cdll.LoadLibrary('dll_testing.dll')
: x.test_fuc(pointer(target())) #我試過此種寫法但失敗
: 但無法實質存取內容
: ------------------------------------
: 若想要將target放入函式中, 請問該如何撰寫呢?
: 煩請先進給予指點了: ) 十分感謝!
如果你沒有指定 native function wrapper 的 argtypes,預設是只能 pass 一些
C 基本的 primitive type 才能正確 marshal 參數到 native function(或者說
wrapper 才知道該如何 marshal 參數值)。
試試這樣的碼(沿用你的 dll 與 structure definition):
# 依照 test_fuc 的 calling convention,適當選擇 cdll or windll
dll = cdll.LoadLibrary("dll_testing.dll")
test_fuc = dll.test_fuc
test.fuc.restype = None
test.fuc.argtypes = POINTER(point), # don't miss the trailing ","
data = (point * 10)()
test.fuc(data)
for p in data:
print p.x, p.y
# pass data 的第 5 個(0-based) element 的位址
test_fuc(byref(data[5]))
# or
test_fuc(pointer(data[5]))
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 118.166.235.101
※ 編輯: sbrhsieh 來自: 118.166.235.101 (08/04 21:31)
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):