免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 11965 | 回复: 1
打印 上一主题 下一主题

python 使用ctypes的byref函数向c传递指针的问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-01-17 18:43 |只看该作者 |倒序浏览
我的目的是想把python结构体指针传递给c函数(c函数已经编译为python的so库),然后C函数获得结构体指针中指向的数据,
我的问题是我的C无法获取到python传给的指针
[root@localhost gcc]# cat etest.h
  1. typedef struct {
  2.     char        name[20];
  3.     int            height;
  4. } Infor;
  5. //char* fact(Infor* haha);
复制代码
C函数
[root@localhost gcc]# cat example.c
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <unistd.h>

  5. typedef struct {
  6.     char        name[20];
  7.     int         height;
  8. } Infor;

  9. int fact(Infor* infor)
  10. {
  11.         int n;
  12.         char* b;
  13.         n = infor->height;
  14.         b = infor->name;
  15.         printf ("%d\n",n);
  16.         return n;
  17. }
复制代码
构造函数
  1. #include <Python.h>
  2. #include "etest.h"
  3. PyObject* wrap_fact(PyObject* self, PyObject* args)
  4. {
  5.   Infor* infor;
  6.   int result;
  7.   
  8.   if (! PyArg_ParseTuple(args, "O:fact", &infor))
  9.     return NULL;
  10.   result = fact(infor);
  11.   return Py_BuildValue("i", result);
  12. }
  13. static PyMethodDef exampleMethods[] =
  14. {
  15.   {"fact", wrap_fact, METH_VARARGS, "Caculate N!"},
  16.   {NULL, NULL}
  17. };
  18. void initexample()
  19. {
  20.   PyObject* m;
  21.   m = Py_InitModule("example", exampleMethods);
  22. }
复制代码
python代码
  1. import os
  2. import sys
  3. import struct
  4. from ctypes import *
  5. import example

  6. class Infor(Structure):
  7.         __fields__ = [('name', c_char*20), ('height', c_int)]

  8. infor = Infor()
  9. infor.name = "hahah"
  10. infor.height = 99

  11. aaa = byref(infor)
  12. print infor.height
  13. a = example.fact(byref(infor))
  14. print a
复制代码
不知道那个环节的传递出了点问题,请教各位高手

论坛徽章:
0
2 [报告]
发表于 2011-01-18 10:17 |只看该作者
没人指点下么...我传递数字和字符是没有问题的
初步怀疑是if (! PyArg_ParseTuple(args, "O:fact", &infor))这里的问题,
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP