I have cython module as below:
cmmodule.pyx:
import ctypes
import os
#... other imports
cdef int doStuff():
print("Do some stuff as administrator")
return 0
cdef public void mainCode():
print("I am doing stuff here")
if ctypes.windll.shell32.IsUserAnAdmin():
if (not os.path.isdir("deco")):
os.mkdir("capture")
doStuff()
else:
hinstance = ctypes.windll.shell32.ShellExecuteW(
None, 'runas', sys.executable, sys.argv[0], None, SW.SHOWNORMAL
)
if hinstance <= 32:
raise RuntimeError(ERROR(hinstance))
cmmodule.pxd:
cdef int doStuff()
cdef public void mainCode()
setup.py:
from distutils.core import setup, Extension
from Cython.Build import cythonize
ext_modules = [
Extension(
"cmmodule",
sources=["cmmodule.pyx",],
),
]
setup(
name="appname",
ext_modules=cythonize(ext_modules),
compiler_directives={'language_level': 3, "unraisable_tracebacks": True}
)
I then build this module using setup.py as python setup.py build_ext --inplace
.
Now I would like to access and run my cython declarations mainCode
in pure C.
run.c:
#include <stdio.h>
#include <Python.h>
#include "cmmodule.h"
int main(){
PyImport_AppendInittab("mainCode", PyInit_cmmodule);
Py_Initialize();
PyImport_ImportModule("mainCode");
__pyx_f_13cmmodule_mainCode();
return 0;
}
Then I compile my run.c code as gcc -o run.exe run.c cmmodule.c -IC:\Users\username\AppData\Local\Programs\Python\Python39\include -IC:\Users\username\A ppData\Local\Programs\Python\Python39\include -LC:\Users\username\AppData\Local\Programs\Python\Python39\libs -lpython39
This compiles just fine, but when I run it, I get the following output:
Problem
I am doing stuff here
NameError: name 'ctypes' is not defined
Exception ignored in: 'commonmodules.mainCode'
NameError: name 'ctypes' is not defined
As you can see in the output, my mainCode
function has been called and it ran the print("I am doing stuff here")
but then it failed to import the ctypes
module from python.
Question
Can anyone tell me, what am I doing wrong here? or what is the proper way to import python modules that are accessible in C?
I tried to move import ctypes
inside my mainCode function as below, which then I got my print output first then the code crashes without any errors, it also doesn't execute ctypes.windll.shell32.IsUserAnAdmin()
line. I am assuming that since the code cannot import ctypes
the program just crashes.
cdef public void mainCode():
print("Running MainCode() here")
import ctypes
if ctypes.windll.shell32.IsUserAnAdmin():
...