从Python调用C函数

时间:2014-07-23 09:36:35

标签: python c call ctypes

我试图使用ctypes从Python调用c函数。

我有三个c文件,两个带有驱动程序(usb-1024LS.c和pmd.c)用于USB设备,另一个带有一些功能(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函数的新手,所以我需要所有的帮助! 谢谢!

1 个答案:

答案 0 :(得分:0)

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

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

我希望这会有所帮助。