简体   繁体   English

使用 ctypes 将 Struct 从 C 返回到 Python 的问题

[英]issue with returning Struct from C to Python using ctypes

I am trying to get the values of C struct member variables from within python using ctypes.我正在尝试使用 ctypes 从 python 中获取 C 结构成员变量的值。 My expected return values for x and y are 10 and 20 respectively.我对 x 和 y 的预期返回值分别是 10 和 20。 I am thinking I might be neglecting something subtle but not sure what it is.我在想我可能忽略了一些微妙但不确定它是什么的东西。 The output I get is 0 for x and y as shown at the end of the post.如帖子末尾所示,我得到的 output 是 x 和 y 的 0。 Any pointers appreciated.任何指针表示赞赏。

Python code: Python 代码:

import ctypes
import os

class Point(ctypes.Structure):
    _fields_ = [("x", ctypes.c_int), 
                ("y", ctypes.c_int)]

directory = os.path.dirname(os.path.realpath(__file__))
print(directory)
source = directory + "\\cstruct.so"
 
clibrary = ctypes.CDLL(source)

clibrary.getPoint.restype = ctypes.POINTER(Point)
p1 = clibrary.getPoint()
print(p1.contents.x, p1.contents.y)

C code: C 代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>


struct Point
{
    int x;
    int y;
};


struct Point* getPoint()
{
    struct Point *p;
    p->x = 10;
    p->y = 20;
    return p;
}

C code is compiled into a shared library file cstruct.so which is called in the python file. C代码编译成共享库文件cstruct.so,在python文件中调用。

Python Output: Python Output:

0 0

I found out what the issue is.我发现了问题所在。 I had to dynamically allocate the size of the struct Point in the C file.我必须在 C 文件中动态分配struct Point的大小。 Previously, I had not done this.以前,我没有这样做。 This solves the issue.这解决了这个问题。

Just modified the first line in the struct Point* getPoint() function as shown below.刚刚修改了struct Point* getPoint() function 中的第一行,如下所示。

struct Point *p = malloc(sizeof(struct Point));

Also added a C function in the c file to free the memory from the struct pointer as shown below.还在 c 文件中添加了 C function 以从结构指针中释放 memory 如下所示。

void free_mem(struct Point* p) 
{
    free(p);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM