0

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

  • Looks like a duplicate of [\[SO\]: Calling a C function with a char\* argument through python ctypes difference python2 and python3](https://stackoverflow.com/q/74867788/4788546). Might be also interesting to read: [\[SO\]: Can't import dll module in Python](https://stackoverflow.com/q/59330863/4788546). – CristiFati Jul 17 '23 at 14:15

1 Answers1

0

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.

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
  • That was it, thanks a lot! I had winmode=1 in it because of initial cdll-problems finding the dll. A bit path fiddling solved this. Great. – broesel09-90 Jul 15 '23 at 15:41