KiYugadgeter
KiYugadgeter

Reputation: 4014

How to access some constant value in C from Python3 with ctypes

How to access pre-defined constant value from python with ctypes?

I have tried get a value, for example SIGTERM (it is clear that value be 15 in my environment x64 linux.) with ctypes.
Following is code that I wrote, but it raise a ValueError (Undefined Symbol). Why this error caused?

Note that I using Ubuntu 19.10, x64, Python 3.7.5

code:

from ctypes import *
from ctypes.util import *
libc_path = find_library("c")
libc = CDLL(libc_path)
sigterm_value = c_int.in_dll(libc, "SIGTERM")

Upvotes: 2

Views: 706

Answers (1)

CristiFati
CristiFati

Reputation: 41137

That is because SIGTERM ([man7]: SIGNAL(7)) is a macro (#define: [GNU.GCC]: Object-like Macros) rather than a constant.
As a consequence, it doesn't reside in libc (meaning that you can't get it via CTypes), but it's just an alias (if you will), that is being replaced by the preprocessor to its value everywhere in (C) source code before compiling.

According to the (official) source file ([SourceWare]: [glibc.git]/bits/signum-generic.h):

#define SIGTERM     15  /* Termination request.  */

In Ubtu 16 64bit (I know it's old, but it's the only Nix VM running at this point), it ends up being defined in /usr/include/bits/signum.h:

#define SIGTERM         15      /* Termination (ANSI).  */

You should use [Python 3.Docs]: signal - Set handlers for asynchronous events:

>>> import signal
>>> signal.SIGTERM
<Signals.SIGTERM: 15>
>>> signal.SIGTERM.value
15

Upvotes: 2

Related Questions