【问题标题】:Structure in ctypectype中的结构
【发布时间】:2022-01-01 16:41:12
【问题描述】:

我是 ctypes 的新手。我已经使用 c 中的结构编写了一个函数。我想使用 ctypes 在 python 中调用它。如果我在 linux 中编译并运行,则没有错误。 但是如果我使用 python 来做,它会抛出错误。

C 程序

#include<stdio.h>
struct add1{
        int a;
        int b;
};

int main(){
        int c;
        struct add1 s;
        printf("Enter 2 no :\n");
        scanf("%d%d",&s.a,&s.b);
        c = s.a + s.b;
        printf("C is : %d",c);
        return c;
}
obj = CDLL("./add12add1.so",mode=1)
print(obj)
#print(obj.add1)


class s(Structure):
    _fields_ = [("a",c_int),("b",c_int)]

c = s(8,9)
#print(c.add1)
print(c.a)
print(c.b)
print(c.a+c.b)
print(c.add1)

AttributeError: 's' 对象没有属性 'add1'

如何解决这个错误?

【问题讨论】:

  • 请发布完整的回溯,以便我们看到失败的行。
  • 另外,发布一些可运行的东西。这意味着导入 ctypes 而不是 obj = CDLL("./add12add1.so",mode=1)。该问题可以在没有导入的情况下重现,因此示例中不需要额外的复杂性。

标签: python c struct structure ctype


【解决方案1】:

您有一个在 C 代码中命名为“add1”的结构,但在 python 代码中将其命名为“s”。它们都有名为“a”和“b”的字段,但都没有名为“add1”的字段。您可以在两个程序中为结构和字段使用不同的名称,它们只需要将数据对齐相同即可。不过,通常情况下,人们会尽量保持相同的名称以避免混淆。我认为这就是这里发生的事情。与C代码匹配的python代码是

class add1(Structure):
    _fields_ = [("a",c_int),("b",c_int)]

s = add1(8,9)
print(s.a)
print(s.b)
print(s.a+s.b)

s.add1 在 python 或 C 代码中不存在,因为add1 不是这两个结构的成员。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-02
    • 1970-01-01
    • 1970-01-01
    • 2012-05-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多