使用ctypes更改共享库中的值

时间:2015-11-06 23:00:51

标签: python ctypes

我有以下lib.c

#include <stdio.h>

double var = 4;

double* fun() {
    printf("%zd %f\n", &var, var);
    return &var;
}

以及以下main.py

import ctypes
lib = ctypes.cdll.LoadLibrary('lib.so')
fun = lib.fun
fun.restype = ctypes.POINTER(ctypes.c_double)

print ctypes.addressof(fun().contents)

我如何在.py内更改存储在double地址的fun().contents,例如,将var设置为10.2

1 个答案:

答案 0 :(得分:2)

以下内容将更改值:

import ctypes
lib = ctypes.cdll.LoadLibrary('x')
fun = lib.fun
fun.restype = ctypes.POINTER(ctypes.c_double)
v = fun()
v.contents.value = 2.0
v = fun()

输出(我使用%p代替%zd的C函数注释):

000007FEFAC14000 4.000000
000007FEFAC14000 2.000000