我想在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))
答案 0 :(得分: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)