在Python中将多个参数传递给C函数

1 投票
1 回答
757 浏览
提问于 2025-04-15 18:36

假设我有一个C语言的库,它可以以某种方式操作一个世界。

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

我有一些函数可以创建和销毁这个世界:

void* create(void);

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]

我该怎么解决这个问题,让它能够正常工作呢?

1 个回答

1

当你执行以下代码时:

def create_world():
    return _create

你并没有调用 _create 这个函数,所以 create_world 返回的是一个函数指针。如果你想要获取指向你世界实例的指针,你应该这样写:

def create_world():
    return _create()

撰写回答