1

I want to access the global variable of c in python. I can already use/access the functions of c in python using ctypes after making a .so file. Here's the C code :

#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;
}

and the Python Code:

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))
2

1 Answer 1

1

Given this one-line source for a Windows DLL:

__declspec(dllexport) int test = 5;

You access global variables by using the .in_dll() method of a ctypes type, which takes a ctypes DLL reference and the name of the global variable:

>>> from ctypes import *
>>> dll = CDLL('test')   # test.dll of the above source.
>>> c_int.in_dll(dll,'test')
c_long(5)
Sign up to request clarification or add additional context in comments.

5 Comments

I want to use it in ubuntu. So how to implement this for .so files
@Akshay Same Python code, I just had a Windows system to test with. Just export a global variable in a .so file.
It is showing me the error of undefined symbol. ValueError: /home/akshay/Desktop/ffmpeg/linking/addr.so: undefined symbol: globalVar
You may need something like __attribute__ ((visibility ("default"))) in Linux to do the equivalent of Windows' __declspec(dllexport) to export the definition from the shared library. See gcc.gnu.org/wiki/Visibility. I don't have a Linux account handy to work it out.
@Akshay extern int globalVar; may also work. My Linux is rusty.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.