【问题标题】:Ctypes - Passing a Void Pointer from PythonCtypes - 从 Python 传递一个空指针
【发布时间】:2016-11-04 01:35:39
【问题描述】:

我在 Windows 7 上使用 Python Ctypes 访问 C++ DLL。我有 DLL 的文档,但实际上无法打开它。我正在尝试使用一个接收函数的 C++ 函数,该函数又接收一个 unsigned int 和一个 void 指针。这是一个失败的简短代码示例:

import ctypes
import os

root = os.path.dirname(__file__)
lib = ctypes.WinDLL(os.path.join(root, 'x86', 'toupcam.dll')) #works

cam = lib.Toupcam_Open(None) #works

def f(event, ctx): #Python version of function to pass in
    pass

#converting Python function to C function:
#CFUNTYPE params: return type, parameter types
func = ctypes.CFUNCTYPE(None, ctypes.c_uint, ctypes.c_void_p)(f)

res = lib.Toupcam_StartPullModeWithCallback(cam, func) #fails

每当我运行此代码时,我都会在最后一行收到此错误:

OSError: exception: access violation writing 0x002CF330.

我真的不知道如何解决这个问题,因为它是 C++ 错误而不是 Python 错误。我认为这与我的 void 指针有关,因为我在网上发现的 C++ 类似错误与指针有关。 Ctypes void 指针有问题,还是我做错了什么?

【问题讨论】:

标签: python c++ ctypes access-violation void-pointers


【解决方案1】:

您需要使用argtypes 声明您调用的函数的参数类型。由于我不知道您的确切 API,因此举个例子:

带有回调的 Windows C DLL 代码:

typedef void (*CB)(int a);

__declspec(dllexport) void do_callback(CB func)
{
    int i;
    for(i=0;i<10;++i)
        func(i);
}

Python 代码:

from ctypes import *

# You can use as a Python decorator.
@CFUNCTYPE(None,c_int)
def callback(a):
  print(a)

# Use CDLL for __cdecl calling convention...WinDLL for __stdcall.
do_callback = CDLL('test').do_callback
do_callback.restype = None
do_callback.argtypes = [CFUNCTYPE(None,c_int)]

do_callback(callback)

输出:

0
1
2
3
4
5
6
7
8
9

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多