Search code examples
python-3.xctypesdynamic-dll-import

Python CDLL: Problem with calling libc-Routines in dll


I'm having trouble with calling libc routines from a self compiled dll loaded with ctypes.CDLL.

Here is a minimal example: DLL is generated in Visual Studio 2022 (OS: Windows 11, everything in 64 bit) with the VS dll standard template for cpp: dllmain.cpp:

// dllmain.cpp : Definiert den Einstiegspunkt für die DLL-Anwendung.
#include "pch.h"

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

#define DLLEXPORT extern "C" __declspec(dllexport)

#include<stdlib.h>
DLLEXPORT int exampl(void) {
    char* ex = (char*) malloc(100 * sizeof(char));
    return(42);
}

After compiling I load the example.dll in a python script (Python 3.9.7) and execute the function: example.py:

import ctypes

lib = ctypes.CDLL("example.dll",winmode=1)
print(lib.exampl())

The result is:

python.exe .\example.py
Traceback (most recent call last):
  File "*<some path>*\example.py", line 4, in <module>
    print(lib.exampl())
OSError: exception: access violation writing 0x0000000000002A3C

The dll Loads fine, but the call of malloc doesn't work.

Similar OSerrors (only with differing "writing" addresses) occur when calling other standard functions from libc as e. g. strncpy or strcmp.

I also tried an cygwin-gcc and a mingw-gcc approach and got the same results. Seems, that something fundamental is missing but I can't find in the documentation what it is.

Can anyone please help?

Thanks in advance broesel09-90


Solution

  • Remove winmode=1. It suppresses loading additional dependencies such as the C runtime DLL that supports malloc. The value is documented in LoadLibraryEx in the Microsoft docs.

    The DllMain function is unnecessary as well but doesn’t hurt.