2

I am trying to load a library in python in Windows 10 (x64).

The cpp file used to generate the library for testing is:

extern "C" int check() {
  return(1);
}

Then I generate the dll with the commands (in x64 Native Tools Command Prompt):

cl /c mylib.cpp
link /dll /machine:x64 mylib.obj

The file mylib.dll is generated. Then in python, which initializes showing the following string:

Python 3.7.4 (default, Aug  9 2019, 18:34:13) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32

I run the following commands:

import ctypes
lib=ctypes.CDLL("mylib.dll")
lib.check.restype=(ctypes.c_int,)

and the last command fails, saying that doesn't recognize check. I also tried lib._check and using a test C file instead of cpp, with the same result, and also tried using ctypes.WinDLL instead of ctypes.CDLL.

What's wrong? Python is x64 as well as the library mylib.dll...

If I do:

ctypes.windll.msvcrt.getchar()

the functions works ok… Here I use the MSVCRT library, which is automatically accessible when I load ctypes.

Should I compile my library differently?

Fabrizio Botalla
  • 697
  • 1
  • 8
  • 25
JDias
  • 126
  • 5
  • 13

1 Answers1

2

You need to export your API:

extern "C" __declspec(dllexport) int check() {
  return 1;
}

Also lib.check.restype should not be a tuple. .argtypes takes a tuple:

lib.check.argtypes = ()
lib.check.restype = ctypes.c_int

FYI, cl /LD mylib.cpp will compile and link a DLL in one step.

Also FYI, CDLL and WinDLL don't matter on x64, but correspond to __cdecl and __stdcall calling convention, respectively, on x86. x64 has only one calling convention so either will work.

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251