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

标签 python c python-3.x ctypes

各位,

我知道我在这里做了一些非常愚蠢的事情,但似乎无法找到解决这个问题的方法,因为我对 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))

关于python - 如何在 C 函数中访问 python 变量的数据? (参数类型 : void *),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34470125/

相关文章:

python - 使用 loc 删除索引过滤的数据框

Python,根据路径创建文件名并替换反斜杠

python - 获取模块为 __main__ 的类对象的模块名称

c - realloc作业帮助

python - Geopy:计算 GPS 航向/方位

python - 我的功能保存到 pickle 不工作

python - 关于正则表达式

c - 学生储物柜拼图

python - 将数据帧年份和月份合并到新对象Python中

c - strtod 返回 0