作者sbrhsieh (偶尔想摆烂一下)
看板Python
标题Re: [问题] 关於ctypes structure之使用
时间Thu Aug 4 20:58:45 2011
※ 引述《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)