el psy Congroo
el psy Congroo

Reputation: 361

How can C.dll expose variable to Python?

I am trying to write a C main program into a dll, and Python will import everything (including all variables and functions) from this dll, and runs the function that is defined in dll. However, I intend to export not only the function but also the variables from DLL to Python. I understand how to expose functions to Python with DLL, but i'm not sure how to access variables from dll with Ctype in Python.

Let's take an example: if inside the header, we have #DEFINE MAXDEVNUMBER 4. when I use ctype print mydll.MAXDENUMBER it threw me an error. function 'MAXDENUM' not found

Variables defined

enter image description here

Upvotes: 2

Views: 1319

Answers (1)

Mark Tolonen
Mark Tolonen

Reputation: 177775

You can't access preprocessor macros because they are not exported from a DLL. You can only access exported C functions and global variables.

For example, test.c:

__declspec(dllexport) int b = 5;

__declspec(dllexport) int func(int a)
{
    return a + b;
}
>>> from ctypes import *
>>> dll = CDLL('test')
>>> dll.func(1)
6
>>> x=c_int.in_dll(dll,'b')  # access the global variable
>>> x.value
5
>>> x.value = 6              # change it
>>> dll.func(1)
7

Upvotes: 5

Related Questions