gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:48:20 24 4
gpt4 key购买 nike

我尝试对 Python 进行 C 扩展。我的问题是我在 C 函数中有 C 函数调用,我已经为其做了 C 扩展。例如,我在这些 C 函数内的 pmd.h 和 usb1024LS.h 中使用了 C 函数。当我尝试运行我的脚本时,我收到类似“undefined symbol: hid_init”的错误。其中 hid_init 是一个函数。我试过在 c 主程序中运行该程序,它可以工作。如何从具有扩展名的其他 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()

设置.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;
}

最佳答案

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


ctypes“声明”是错误的:void 与 void 指针 (void*) 不同。 findInterface() C 函数既没有参数也没有返回值,“声明”为:

ctypes_findInterface.argtypes = []
ctypes_findInterface.restype = None

关于python - 在 Python 的 C 扩展中调用 C 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24950876/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com