0

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():

    ...
sdfdf
  • 3
  • 3
  • A couple of quick pointers: 1) `PyImport_ImportModule` returns `NULL` if it fails, so it's worth checking that. 2) The main issue will be to do Python's search path, which isn't set by default in embedded Python. Use `PySys_SetPath` to set that. – DavidW Apr 26 '23 at 17:01
  • @DavidW, is it possible make the run.exe standalone, so that when compiled by GCC, it should not require any python header files? – sdfdf Apr 26 '23 at 21:31
  • Also, as you suggested, I checked if `PyImport_importModule` fails to load mainCode and it indeed does fail:` if(PyImport_ImportModule("mainCode") == NULL){ printf("Failed to import mainCode\n"); }` – sdfdf Apr 26 '23 at 21:33
  • adding `PySys_SetPath("C:/Users/username/AppData/Local/Programs/Python/python39");` after `Py_Initialize()`, I now get `ModuleNotFoundError: No module named 'xyz'`. xyz.pyx is another module that is used in my cmmodules.pyx. In other words I have `cimport xyz` in my cmmodules.pyx – sdfdf Apr 26 '23 at 23:55
  • You probably want `"C:/Users/username/AppData/Local/Programs/Python/python39;."` - the `.` adds the current directory. – DavidW Apr 27 '23 at 02:22
  • "1is it possible make the run.exe standalone, so that when compiled by GCC, it should not require any python header files"- **No**. https://stackoverflow.com/a/59389683/4657412. Cython is not the solution for this. Don't waste your time trying – DavidW Apr 27 '23 at 02:25
  • I added '.' to the path, but am still getting the same error as xyz.pyx module is not found – sdfdf Apr 27 '23 at 15:42
  • Also, when I compile my run.exe I run `gcc run.c cmmodule.c xyz.c ...` – sdfdf Apr 27 '23 at 17:30
  • @DavidW, would you have any other suggestiongs? setting . and python path using `PySys_SetPath` didnt work :( – sdfdf May 02 '23 at 21:30

0 Answers0