从Python调用C函数
我正在尝试通过ctypes在Python中调用C语言的函数。
我有三个C语言文件,其中两个是用于USB设备的驱动程序(usb-1024LS.c和pmd.c),还有一个是用来测试这些驱动程序的函数文件(myTest_1024LS.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
我最近问过一个类似的问题,但我不知道你的问题是否和我的有关(我还是个新手)。我遇到了调用约定的问题,而你遇到了未定义符号,看起来有点相似,所以我建议你看看我遇到的问题:用ctypes在Python中封装C++函数,还有它的被接受的回答,读起来也不算太长。
你说可能是编译器的问题,但你是在运行Python脚本,对吧?你是指Python解释器,还是在运行脚本之前的C编译器?你有没有尝试过用你的C库构建一个C主程序,测试一下和libusb的通信,而不使用任何Python?
希望这些能帮到你。