在Python的C扩展中调用C函数

问题描述:

我试图对Python做一个C扩展。我的问题是,我有C函数内的C函数,我做了一个C扩展。例如,我在这些C函数中使用pmd.h和usb1024LS.h中的C函数。当我尝试运行我的脚本时,出现“undefined symbol:hid_init”等错误。 hid_init是一个函数。 我曾尝试在c主程序中运行该程序,并且它可以正常工作。 如何从具有扩展名的其他C函数内部调用C函数?在Python的C扩展中调用C函数

谢谢!

我的代码: test.py - 测试脚本:

import ctypes 
import myTest_1024LS 

ctypes_findInterface = ctypes.CDLL('/home/oysmith/NetBeansProjects/MCCDAQ/usb1024LS_with_py/myTest_1024LS.so').findInterface 
ctypes_findInterface.restype = ctypes.c_void_p 
ctypes_findInterface.argtypes = [ctypes.c_void_p] 

ctypes_findInterface() 

setup.py:

from distutils.core import setup, Extension 

setup(name="myTest_1024LS", version="0.0", ext_modules = [Extension("myTest_1024LS", ["myTest_1024LS.c"])]) 

myTest_1024LS.c:

#include <stdlib.h> 
#include <stdio.h> 
#include <string.h> 
#include <unistd.h> 
#include <fcntl.h> 
#include <ctype.h> 
#include <sys/types.h> 
#include <asm/types.h> 
#include <python2.7/Python.h> 

#include "pmd.h" 
#include "usb-1024LS.h" 
#include "myTest_1024LS.h" 

void findInterface(void){ 
int interface; 
hid_return ret; 
ret = hid_init(); 
if (ret != HID_RET_SUCCESS) { 
     fprintf(stderr, "hid_init failed with return code %d\n", ret); 
     exit(1); 
} 

if ((interface = PMD_Find_Interface(&hid, 0, USB1024LS_PID)) >= 0) { 
     printf("USB 1024LS Device is found! interface = %d\n", interface); 
} else if ((interface = PMD_Find_Interface(&hid, 0, USB1024HLS_PID)) >= 0) { 
     printf("USB 1024HLS Device is found! interface = %d\n", interface); 
} else { 
     fprintf(stderr, "USB 1024LS and USB 1024HLS not found.\n"); 
     exit(1); 
} 
} 

PyDoc_STRVAR(myTest_1024LS__doc__, "myTes_1024LS point evaluation kernel"); 
PyDoc_STRVAR(findInterface__doc__, "find device"); 

static PyObject *py_findInterface(PyObject *self, PyObject *args); 

static PyMethodDef wrapper_methods[] = { 
{"findInterface", py_findInterface, METH_VARARGS, findInterface__doc__}, 
{NULL, NULL} 
}; 

PyMODINIT_FUNC initwrapper(void){ 
Py_InitModule3("wrapper", wrapper_methods, myTest_1024LS__doc__); 

} 

static PyObject *py_findInterface(PyObject *self, PyObject *args){ 

if(!PyArg_ParseTuple(args, "")){ 
    return NULL; 
} 
findInterface(); 
return 0; 
} 
+0

你想运行一个Python脚本调用C函数,然后将再次调用Python函数?如果我说得对:如何重写C中的内部Python函数?毕竟,我想你想通过切换到C(可能是速度?)来达到某种程度,然后再回到Python可能会破坏这种乐趣。 – Alfe

+0

不,我有一个Python脚本调用C函数,调用另一个C函数,就像你在myTest_1024LS.c中看到的一样。 C函数内部的C函数调用是对USB设备驱动程序的调用。我不想为所有驱动程序函数编写C语言,因为它们中有很多。 –

+0

我明白了。您是如何照顾USB驱动程序所需的库链接到您的代码的? – Alfe

在构建C扩展其本身必须链接到其他共享库,你必须告诉哪些链接setup.py。在这种情况下,至少要导出hid_init()函数库。有关更多详细信息和示例,请参阅Python文档:Building C and C++ Extensions with distutils。第二个示例包含将一个额外的库链接到扩展模块的参数。


的​​“声明”是错误的:void是不一样的一个空指针(void*)。该findInterface() C函数既没有参数也没有返回值,这是“申报”为:

ctypes_findInterface.argtypes = [] 
ctypes_findInterface.restype = None