相关疑难解决方法(0)

将元组扩展为参数

有没有办法将Python元组扩展为函数 - 作为实际参数?

例如,这里expand()有魔力:

some_tuple = (1, "foo", "bar")

def myfun(number, str1, str2):
    return (number * 2, str1 + str2, str2 + str1)

myfun(expand(some_tuple)) # (2, "foobar", "barfoo")
Run Code Online (Sandbox Code Playgroud)

我知道可以定义myfunmyfun((a, b, c)),但当然可能有遗留代码.谢谢

python tuples parameter-passing

375
推荐指数
5
解决办法
20万
查看次数

通过 ctypes 从 Python 调用的 C 函数返回不正确的值

我用 C 编写了一个简单的函数,它可以将给定的数字提高到给定的幂。当我在 C 中调用它时,该函数返回正确的值,但是当我在 Python 中调用它时,它返回一个不同的、不正确的值。

我使用以下命令创建了共享文件: $ gcc -fPIC -shared -o test.so test.c

我尝试了 C 函数的不同配置,其中一些返回预期值,而另一些不返回。例如,当我的函数使用return x*x没有for循环的简单正方形时,它在 Python 中返回了正确的值。

我希望最终能够在 python 中调用一个 C 函数,该函数将返回一个二维 C 数组。

#include <stdio.h>

float power(float x, int exponent)
{
    float val = x;
    for(int i=1; i<exponent; i++){
        val = val*x;
    }
    return val;
}
Run Code Online (Sandbox Code Playgroud)
#include <stdio.h>

float power(float x, int exponent)
{
    float val = x;
    for(int i=1; i<exponent; i++){
        val = val*x;
    }
    return val;
}
Run Code Online (Sandbox Code Playgroud)

我在 C …

c python ctypes

3
推荐指数
1
解决办法
1816
查看次数

标签 统计

python ×2

c ×1

ctypes ×1

parameter-passing ×1

tuples ×1