【问题标题】:Passing multiple arguments to C function within Python在 Python 中将多个参数传递给 C 函数
【发布时间】:2010-01-28 15:53:53
【问题描述】:

假设我有一个以某种方式操纵世界的 c 库。

我想在 python 中使用这个库。我希望能够编写简单的 Python 脚本来代表世界管理的不同场景。

我有创建和摧毁世界的功能: 无效*创建(无效); int destroy(void* world);

这是一些python代码:

import ctypes

lib = ctypes.CDLL('manage_world.so')

_create = lib.create
_create.restype = ctypes.c_void_p

_destroy = lib.destroy
_destroy.argtypes = [ctypes.c_void_p,]
_destroy.restype = ctypes.c_int

def create_world():
    res =  _create()
    res = ctypes.cast(res, ctypes.c_void_p)
    return res

def destroy_world(world):
    return _destroy(world)

new_world = create_world()
print type(new_world)

print destroy_world(new_world)

现在我想添加如下功能: int set_world_feature(void* world, feature_t f, ...); int get_world_feature(void* world, feature_t f, ...);

问题是在我的 python 包装器中,我不知道如何传递不同的多个参数。

因为有时 set_world_feature() 会使用 3 或 4 个参数调用。

再次在 Python 中:

def set_world_feature(world, *features):
    res = lib.set_world_feature(world, *features)
    return world_error[res]

如何解决此问题以使其正常工作?

【问题讨论】:

    标签: python arguments ctypes


    【解决方案1】:

    当你这样做时:

    def create_world():
        return _create
    

    你没有调用_create,所以create_world返回函数指针。如果你想要指向你的世界实例的指针,你应该改写:

    def create_world():
        return _create()
    

    【讨论】:

      猜你喜欢
      • 2018-10-29
      • 1970-01-01
      • 2016-04-02
      • 1970-01-01
      • 2014-10-22
      • 2021-11-11
      • 1970-01-01
      相关资源
      最近更新 更多