在python ctypes中声明变量并传递给dll函数

时间:2018-07-16 08:50:03

标签: c++ python-2.7 ctypes

例如,我有一个C ++变量声明和类似这样的函数(假定其为dll函数)


    int img_width, img_height, stride;
    somefunction(&img_width, &img_height, &stride)
    {
    ....
    }

同样的事情,我们该如何使用python ctypes?

我尝试过以下方式

img_width, img_height, stride = c.POINTER(c_int), c.POINTER(c_int), c.POINTER(c_int)
dll.somefunction(img_width, img_height, stride)

这导致了以下异常

ctypes.ArgumentError: argument 1: : Don't know how to convert parameter 1)

我也尝试了以下方式

dll.somefunction.restype = c.c_void_p
dll.somefunction.argtypes = [c.POINTER(c_int), c.POINTER(c_int), c.POINTER(c_int)]
dll.somefunction(img_width, img_height, stride)

我在哪里遇到以下异常

NameError: global name 'img_width' is not defined

1 个答案:

答案 0 :(得分:0)

您正在创建需要创建整数实例并通过引用传递的类型:

from ctypes import *

# Declare the argument types
dll.somefunction.argtypes = POINTER(c_int), POINTER(c_int), POINTER(c_int)

# Create instances of the types needed
img_width, img_height, stride = c_int(), c_int(), c_int()

# Pass by reference
dll.somefunction(byref(img_width), byref(img_height), byref(stride))
相关问题