创建python绑定时出错
此C语言程序运行和编译良好:创建python绑定时出错,python,c,gcc,binding,shared,Python,C,Gcc,Binding,Shared,此C语言程序运行和编译良好: #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <stdio.h> #include <string.h> #include <errno.h> #include <getopt.h> #include <atasmart.h> int main(){ const char *device = "/dev/sda"; int
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <getopt.h>
#include <atasmart.h>
int main(){
const char *device = "/dev/sda";
int ret;
uint64_t ms;
SkDisk *d;
if ((ret = sk_disk_open(device, &d)) < 0) {
printf("Failed to open disk\n");
return 1;
}
if ((ret = sk_disk_smart_read_data(d)) < 0) {
printf("Failed to read SMART data: \n");
}
if ((ret = sk_disk_smart_get_power_on(d, &ms)) < 0) {
printf("Failed to get power on time:\n");
}
printf("%llu\n", (unsigned long long) ms);
return 0;
}
但是,在尝试基于该程序创建python绑定时:
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <getopt.h>
#include <atasmart.h>
#include <Python.h>
static PyObject *pySmart_powerOn(PyObject *self, PyObject *args)
{
const char *device = "/dev/sda";
int ret;
uint64_t ms;
SkDisk *d;
if (!PyArg_ParseTuple(args, "s", &device))
{
return NULL;
}
if ((ret = sk_disk_smart_get_power_on(d, &ms)) < 0) {
return Py_BuildValue("s", "Failed to get power on time");
}
return Py_BuildValue("K", (unsigned long long) ms);
}
static PyMethodDef pySmart_methods[] = {
{ "powerOn", (PyCFunction)pySmart_powerOn, METH_VARARGS, NULL },
{ NULL, NULL, 0, NULL }
};
PyMODINIT_FUNC initpySmart()
{
Py_InitModule3("pySmart", pySmart_methods, "Trial module");
}
然后我得到如下警告:,但该文件已编译
In file included from /usr/include/python2.7/Python.h:8:0,
from atabind.c:12:
/usr/include/python2.7/pyconfig.h:1158:0: warning: "_POSIX_C_SOURCE" redefined [enabled by default]
/usr/include/features.h:214:0: note: this is the location of the previous definition
当我在Python中运行时
import pySmart
我明白了
ImportError: ./pySmart.so: undefined symbol: sk_disk_smart_get_power_on
我猜是因为我用错误的标志/选项编译了pySmart.so共享库而导致错误。。但是我想不出来 您需要在源文件之后指定链接器标志(
-lfoo
)。这是因为链接器的工作方式:当您为它指定一个库时,它会检查库中到目前为止所需的符号。如果不需要符号(就好像你还没有找到任何源对象),它只会跳过库
请尝试以下命令行:
gcc -shared -I/usr/include/python2.7 \
`pkg-config --cflags libatasmart` \
atabind.c \
`pkg-config --libs libatasmart` \
-o pySmart.so -fPIC
您应该首先包括Python.h,然后是任何std头 使用Python/CAPI所需的所有函数、类型和宏定义都包含在您的代码中
#包括“Python.h”
这意味着包含以下标准标题:
、和
(如果可用)
由于Python可能会定义一些影响某些系统上标准头的预处理器定义,因此必须在包含任何标准头之前包含Python.h
或者:
只要
\u GNU_SOURCE
,它就会被GNU libc的/usr/include/features.h忽略,当你厌倦了手工操作后,就开始使用distutils:@ThomasWouters,我完全同意。然而,手工做事有时具有很好的教育性质<代码>;)代码>确实如此。因此,“疲劳后”:(非常感谢,它起作用了。将首先指定源文件。是第一次这样做,因此手动。。。从现在开始,一定要使用distutils。谢谢
ImportError: ./pySmart.so: undefined symbol: sk_disk_smart_get_power_on
gcc -shared -I/usr/include/python2.7 \
`pkg-config --cflags libatasmart` \
atabind.c \
`pkg-config --libs libatasmart` \
-o pySmart.so -fPIC