【问题标题】:Calling C-functions from Python从 Python 调用 C 函数
【发布时间】:2014-07-23 09:36:35
【问题描述】:

我正在尝试使用 ctypes 从 Python 调用 c 函数。

我有三个 c 文件,两个带有用于 USB 设备的驱动程序(usb-1024LS.c 和 pmd.c),一个带有一些功能(myTest_1024LS.c)来测试驱动程序。驱动程序 c 文件正在使用 libusb。当我尝试运行我的脚本时,编译器似乎找不到 libusb。我得到了错误:

File "/usr/lib/python2.7/ctypes/__init__.py", line 365, in __init__
self._handle = _dlopen(self._name, mode)
OSError: /path-to-folder/usb1024LS_with_py/pmd.so: undefined symbol: usb_get_driver_np

usb_get_driver_np 是 libusb 中的一个函数。

我的 Python 脚本:

import ctypes

pmd = ctypes.CDLL('/home/oysmith/NetBeansProjects/MCCDAQ/usb1024LS_with_py/pmd.so');
usb1024LS = ctypes.CDLL('/home/oysmith/NetBeansProjects/MCCDAQ/usb1024LS_with_py/usb-1024LS.so');
testFunc = ctypes.CDLL('/home/oysmith/NetBeansProjects/MCCDAQ/usb1024LS_with_py/myTest_1024LS.so');

# declare the function we use
testFunc.writeByte.argtypes = (ctypes.c_void_p,)
testFunc.writeByte.restype = ctypes.c_void_p

testFunc.findInterface.argtypes = (ctypes.c_void_p,)
testFunc.findInterface.restype = ctypes.c_void_p

pmd.PMD_GetInputReport.argtypes = (ctypes.c_char_p, ctypes.c_uint, ctypes.c_uint, ctypes.c_int, ctypes.c_int,)
pmd.PMD_GetInputReport.restype = ctypes.c_char_p, ctypes.c_uint, ctypes.c_uint, ctypes.c_int, ctypes.c_int

#call C function 
testFunc.findInterface()

findInterface 调用 pmd.c 中的函数,而 pmd.c 中的函数调用 libusb 中的函数。

我是从 Python 调用 c 函数的新手,所以我需要我能得到的所有帮助! 谢谢!

【问题讨论】:

  • 如果从运行 python/程序的终端运行“ldd /path-to-folder/usb1024LS_with_py/pmd.so”,输出是什么?是否所有依赖项都已解决/可用?
  • 然后我得到这个输出:linux-vdso.so.1 => (0x00007fffcfe8b000) libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f0693615000) /lib64/ld-linux-x86-64.so.2 (0x00007f0693bf7000)

标签: python c call ctypes


【解决方案1】:

我最近问了一个类似的问题,但我不知道你的问题是否与我有关(我是初学者),我遇到了调用约定问题,并且你有未定义的符号,看起来很接近,所以我建议您可以阅读我的问题:Wrapping c++ functions with ctypes 及其已接受的答案,阅读时间不会很长。

您说它可能是编译器,但您正在运行 python 脚本,对吗?您是指运行脚本之前的python解释器还是C编译器?您是否尝试过使用您的 C 库构建一个 C 主程序来测试与 libusb 的通信而无需任何 python?

我希望这会有所帮助。

【讨论】:

  • 我去看看,谢谢!我制作了一个 C 主程序并验证了这些功能是否有效。是的,我用了python解释器,编译c文件可以正常工作!
猜你喜欢
  • 2013-08-30
  • 2011-05-18
  • 1970-01-01
  • 2010-12-02
  • 2016-03-25
  • 2016-05-29
  • 1970-01-01
  • 2021-02-07
相关资源
最近更新 更多