37,720
社区成员
发帖
与我相关
我的任务
分享
typedef struct {
char name[20];
int height;
int weight;
} Infor;
int getInfor( char* name, int height, int weight, Infor* infor);
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "Extest.h"
int getInfor( char* name, int height, int weight, Infor* infor)
{
if(name == NULL || infor == NULL)
return (-1);
printf(" [%s] get params: name[%s] height[%d] weight[%d]\n", __FUNCTION__, name, height, weight);
strcpy(infor->name, name);
infor->height = height;
infor->weight = weight;
return (1);
}
#include "Python.h"
#include "ceval.h"
#include "Extest.h"
static PyObject * Extest_getInfor(PyObject *self, PyObject *args)
{
char* name;
int height;
int weight;
Infor* infor;
int res;
if(!PyArg_ParseTuple(args, "siiO:infor", &name, &height, &weight, &infor)){
return NULL;
}
printf(" ***** Before Call: infor.name[%s] infor.height[%d] infor.weight[%d] *****\n",infor->name, infor->height, infor->weight);//【1】初始值
res = getInfor(name, height, weight, infor);
printf(" ***** After Call: infor.name[%s] infor.height[%d] infor.weight[%d] *****\n", infor->name, infor->height, infor->weight);//【2】改变后的值
return (PyObject*)Py_BuildValue("i", res);
}
static PyMethodDef ExtestMethods[] = {
{ "getInfor", Extest_getInfor, METH_VARARGS },
{ NULL, NULL },
};
void initExtest(void)
{
PyObject *m;
m = Py_InitModule("Extest", ExtestMethods);
}
# Makefile of Extend C for Python
OBJS = Extest.o ExtestWrappers.o
SOLIBS =
SOLIBDIR =
TARGET = Extest.so
INCLUDES = -I /usr/local/include/python2.6/
MAKEFILE = Makefile
CC = gcc
DEBUG =
CFLAGS = -fPIC -Wall -Wstrict-prototypes -Winline \
${INCLUDES} -O2 $(DEBUG)
all : ${TARGET}
${TARGET} : ${OBJS} ${LIBS}
${CC} -shared -o ${TARGET} ${OBJS} ${SOLIBS} ${SOLIBDIR}
rm -f ${OBJS}
clean :
rm -f *.o *.Z* *~ ${TARGET}
#!/usr/bin/env python2.6
#coding=utf8
#----- 调用扩展C程序接口的测试程序 -----#
import Extest
from ctypes import *
class Infor(Structure):
_fields_= [('name', c_char*20),
('height', c_int),
('weight', c_int)]
def main():
infor = Infor()
infor.name = 'NoName'
infor.height = -1
infor.weight = -1
name = 'TestName'
height = 175
weight = 160
print 'Before call getInfor(), Infor.name=%s Infor.height=%d Infor.weight=%d' % (infor.name, infor.height, infor.weight)
Extest.getInfor(name, height, weight, byref(infor))
print 'After call getInfor(), Infor.name=%s Infor.height=%d Infor.weight=%d' % (infor.name, infor.height, infor.weight) #【3】测试返回的结构体
print ' ----- all DONE -----'
if __name__ == '__main__':
main()
[root@localhost obj_struct_test]# ./test.py
Before call getInfor(), Infor.name=NoName Infor.height=-1 Infor.weight=-1
sizeof(*infor)=28, sizeof(Infor)=28
***** [Extest_getInfor] Before Call: infor.name[] infor.height[0] infor.weight[0] *****
[getInfor] get params: name[TestName] height[175] weight[160]
***** [Extest_getInfor] After Call: infor.name[TestName] infor.height[175] infor.weight[160] *****
After call getInfor(), Infor.name=NoName Infor.height=-1 Infor.weight=-1
----- all DONE -----