【问题标题】:Calling global variable of C in Python在 Python 中调用 C 的全局变量
【发布时间】:2018-06-20 13:16:25
【问题描述】:

我想在python中访问c的全局变量。在制作 .so 文件后,我已经可以使用 ctypes 在 python 中使用/访问 c 的功能。 这是 C 代码:

#include <stdio.h>

int globalVar = 2;

void add_int(int num1,int num2){
    globalVar = num1+num2;
    fprintf(globalVar, "%d\n", );
}

float add_float(float num1,float num2){
    return num1+num2;
}

和 Python 代码:

from ctypes import *

adder = CDLL('/home/akshay/Desktop/ffmpeg/linking/addr.so')

adder.add_int(4,5)

var = c_int.in_dll(adder,"globalVar")
print "Sum of 4 and 5 = " + str(adder.add_int(4,5))

a = c_float(5.5)
b = c_float(4.1)

add_float = adder.add_float
add_float.restype = c_float
print "Sum of 5.5 and 4.1 = ", str(add_float(a, b))

【问题讨论】:

标签: c python-2.7 ctypes


【解决方案1】:

鉴于此 Windows DLL 的单行源代码:

__declspec(dllexport) int test = 5;

您可以使用 ctypes 类型的 .in_dll() 方法访问全局变量,该方法接受 ctypes DLL 引用和全局变量的名称:

>>> from ctypes import *
>>> dll = CDLL('test')   # test.dll of the above source.
>>> c_int.in_dll(dll,'test')
c_long(5)

【讨论】:

  • 我想在ubuntu中使用。那么如何为 .so 文件实现这一点
  • @Akshay 相同的 Python 代码,我只是有一个 Windows 系统来测试。只需在 .so 文件中导出一个全局变量。
  • 它向我显示未定义符号的错误。 ValueError:/home/akshay/Desktop/ffmpeg/linking/addr.so:未定义符号:globalVar
  • 您可能需要类似 Linux 中的 __attribute__ ((visibility ("default"))) 来执行相当于 Windows 的 __declspec(dllexport) 以从共享库中导出定义。见gcc.gnu.org/wiki/Visibility。我没有方便的 Linux 帐户来解决这个问题。
  • @Akshay extern int globalVar; 也可以工作。我的 Linux 生锈了。
猜你喜欢
  • 2012-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-14
  • 2012-01-31
  • 2012-10-25
  • 1970-01-01
  • 2019-07-24
相关资源
最近更新 更多