【问题标题】:access python ctypes structure from c shared library从 c 共享库访问 python ctypes 结构
【发布时间】:2012-02-13 12:51:51
【问题描述】:

我写了一个python代码来将ctypes结构传递给c库函数

python 代码:

from ctypes import *

class Info(Structure):
   _field_ = [("input",c_int),
              ("out",c_int)]

info = Info()

info.input = c_int(32)
info.out = c_int(121)

lib = CDLL("./sharedLib.so").getVal
a = lib(byref(info))

c 代码:

#include <stdio.h>

struct info{
    int input;
    int out;
};

void getVal(struct info *a){
    printf("in = %i \n", a->input);
    printf("out = %i \n", a->out);
}

使用命令编译它: gcc -shared -fPIC -o sharedLib.so sharedLib.c

输出:

in = 0 
out = 0 

我的问题是,为什么输出与我在 python 代码中设置的值不同。有什么解决办法吗? 我在 32 位环境中

【问题讨论】:

    标签: python c ctypes


    【解决方案1】:

    在 ctypes 结构定义中,您写的是 _field_ 而不是 _fields_。因此,这些字段不会被翻译成它们的 C 等价物。

    【讨论】:

      【解决方案2】:

      尝试添加:

      lib.argtypes = [POINTER(Info)]
      

      在调用 lib 之前。

      【讨论】:

      • +1 表示设置 argtypes 的建议,通常也可以设置 restype。如果你同时设置了这两个,Python 会通过做一些检查来尽力保护用户免受 seg 错误的影响。
      猜你喜欢
      • 1970-01-01
      • 2015-09-10
      • 1970-01-01
      • 1970-01-01
      • 2012-07-02
      • 1970-01-01
      • 1970-01-01
      • 2012-10-17
      • 2012-03-26
      相关资源
      最近更新 更多