如何在 C 函数中访问 python 变量的数据? (参数类型:void *)

How to access a python variable's data inside a C function? (Argument type: void *)

各位,

我知道我在这里做了一些非常愚蠢的事情,但似乎找不到解决这个问题的方法,因为我对 python 中的 ctypes 相对不熟悉。简化代码以提高可读性。

我在名为 'LibTest.so' 的共享库中有以下函数:

#include<stdio.h>
#include<stdint.h>

void test(void *val1, void *val2) {

    printf("\nAddress of val1 = %x, val2 = %x\n", val1, val2);

    printf("\nval1 = %llu, val2 = %llu\n", *(uint64_t *)val1, *(uint64_t *)val2);
}

我在 Python (3.4.4) 程序中使用 ctypes 以下列方式调用上述函数:

import sys
from ctypes import *
lib = './LibTest.so'
dll = CDLL(lib)

dll.test.argtypes = [c_void_p, c_void_p]
dll.test.restype = None

def test(val1, val2):

# I am guessing the next 3 lines of code need a fix to make this work

    val1 = c_void_p()
    val2 = c_void_p()
    dll.test(byref(val1), byref(val2))


if __name__ == '__main__':

    val1 = 7122253
    val2 = 2147483647
    test(val1, val2)
    sys.exit(0)

为此我得到以下(意外)输出:

Address of val1 = 7d824780, val2 = 7d8249a0

val1 = 0, val2 = 0

但是当我在 C 程序中调用同一个函数时,它起作用了:

  #include<stdio.h>
  #include<stdint.h>

  int main(){

  uint64_t val1 = 2147483647;
  uint64_t val2 = 7122253;

  void *ptr1, *ptr2;
  ptr1 = &val1;
  ptr2 = &val2;

  test(ptr1, ptr2);

  return(0);
}

输出为:

Address of val1 = ffbff8a0, val2 = ffbff898

val1 = 2147483647, val2 = 7122253

关于如何做到这一点有什么建议吗?感谢您的帮助!

您的 python test() 函数从不使用其参数。这可能是你想要做的:

def test(val1, val2):
    val1 = c_void_p(val1)
    val2 = c_void_p(val2)
    dll.test(byref(val1), byref(val2))