python - 如何从 python 对象中检索值?

标签 python c object

我尝试使用 python 对象与 python 进行通信。在 c 端,我将值存储到指针变量。当我返回它时,我在 python 端得到一个 python 对象。是否有可能在 python 端检索“来自 python 对象的那些指针值”?

测试.c文件

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


    int *getval() {
        int  *var;
        int *var1;
        int i;
        var1=var;
        *var=5;
        var++;
        *var=6;
        return var1;
    }

test1.c file

    #include <Python.h>

        static PyObject * getvals(PyObject * self, PyObject * args)
        {
            int *x;
            x=getval();
            PyObject * test = PyCapsule_New((int *)x, "int", NULL);
            return test;

        }


python file

    import test1
    x=test1.getvals()

something like this .. I want to get the values of the var file I have assigned in test.c in python file.

我对此进行了修改,请检查如何在 python 端检索值

test.c
uint64_t * getvar()
{
    int i=0;
    uint64_t * vars=(uint64_t *)malloc(sizeof(uint64_t));

        for(i=0;i<3;i++)
        {
            var[i]=i;
            printf("%llu\n",var[i]);
        }
    return vars;
}
test1.c
static PyObject * getlist(PyObject * self, PyObject * args)
{
    int i;
    uint64_t *  mylist;
    mylist=getvar();
    for(i=0;i<3;i++)
        printf("%llu\n",mylist[i]);
    PyObject * my_list = PyCapsule_New((void *)my_list, "uint64_t", NULL);
    return my_list;
}
test.py

import test1
x=test.getvals()
print x

在编译 c 文件时,我收到这样的警告

format ‘%llu’ expects argument of type ‘long long unsigned int’, but argument 2 has type ‘uint64_t’ [-Wformat]

warning: ‘vars’ may be used uninitialized in this function [-Wuninitialized]

但仍然打印出值,我如何初始化“vars”?以及如何在 test.py 中检索 test.c 中分配的值

请建议..

最佳答案

你的代码严重损坏。您的 getval 函数将数据存储在内存中的随机位置。这很容易损坏并可能最终导致程序崩溃。

*var=5;

要实现此功能,var 需要指向某个内容。但 var 并不指向任何东西,因为你从未设置过它。

我猜你了解 python 并且刚刚开始使用 C。我建议你在尝试一起使用 python 和 c 之前先自学 C 一段时间。你的 C 代码表明你对 C 的工作原理非常困惑,并且在解决这个问题之前使用 Python/C api 会非常困难。

关于python - 如何从 python 对象中检索值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9956074/

相关文章:

javascript - 数组元素和对象属性比较返回 false

c++ - 有条件地为变量分配一个类

python - 如何使用pyrebase查询?

c - 如何使用 libetpan 在 HTML mime 消息中嵌入图像

c - 数组名是指针吗?

c - C 和 ncurses 中的 ANSI 颜色

java - 什么样的集合类来获取数组中的位置?

python - 为什么 exec 不定义我的变量?

python - group_by 返回重复的键

php - 如何在 php 中像 python argparse 一样获得 getop() 的高级用法