windows common item dialog: ctypes + com access violation

  • Last Update :
  • Techknowledgy :

Change the line

func_proto = ctypes.WINFUNCTYPE(HRESULT, HWND)


func_proto = ctypes.WINFUNCTYPE(HRESULT, c_long, HWND)

and this line


Suggestion : 2


from random
import random
from time
import perf_counter

COUNT = 500000 # Change this value depending on the speed of your computer
DATA = [(random() - 0.5) * 3
   for _ in range(COUNT)

e = 2.7182818284590452353602874713527

def sinh(x):
   return (1 - (e ** (-2 * x))) / (2 * (e ** -x))

def cosh(x):
   return (1 + (e ** (-2 * x))) / (2 * (e ** -x))

def tanh(x):
   tanh_x = sinh(x) / cosh(x)
return tanh_x

def test(fn, name):
   start = perf_counter()
result = fn(DATA)
duration = perf_counter() - start
print('{} took {:.3f} seconds\n\n'.format(name, duration))

for d in result:
   assert - 1 <= d <= 1, " incorrect values"

if __name__ == "__main__":
   print('Running benchmarks with COUNT = {}'.format(COUNT))

test(lambda d: [tanh(x) for x in d], '[tanh(x) for x in d] (Python implementation)')

In the C++ project's module.cpp file, add the following code:

#include <Windows.h>
#include <cmath>

const double e = 2.7182818284590452353602874713527;

double sinh_impl(double x) {
    return (1 - pow(e, (-2 * x))) / (2 * pow(e, -x));

double cosh_impl(double x) {
    return (1 + pow(e, (-2 * x))) / (2 * pow(e, -x));

double tanh_impl(double x) {
    return sinh_impl(x) / cosh_impl(x);

At the top of the module.cpp file, include Python.h:

#include <Python.h>

Modify the tanh_impl method to accept and return Python types (that is, a PyObject*):

PyObject * tanh_impl(PyObject * /* unused module reference */ , PyObject * o) {
   double x = PyFloat_AsDouble(o);
   double tanh_x = sinh_impl(x) / cosh_impl(x);
   return PyFloat_FromDouble(tanh_x);

Add a structure that defines how the C++ tanh_impl function is presented to Python:

static PyMethodDef superfastcode_methods[] = {
   // The first property is the name exposed to Python, fast_tanh
   // The second is the C++ function with the implementation
   // METH_O means it takes a single PyObject argument
      (PyCFunction) tanh_impl,

   // Terminate the array with an object containing nulls.

In the following example, the "superfastcode" module name means that you can use from superfastcode import fast_tanh in Python, because fast_tanh is defined within superfastcode_methods. File names that are internal to the C++ project, such as module.cpp, are inconsequential.

static PyModuleDef superfastcode_module = {
   "superfastcode", // Module name to use with Python import statements
   "Provides some functions, but faster", // Module description
   superfastcode_methods // Structure that defines the methods of the module

Suggestion : 3

On Windows creating a CDLL instance may fail even if the DLL name exists. When a dependent DLL of the loaded DLL is not found, a OSError error is raised with the message “[WinError 126] The specified module could not be found”. This error message does not contain the name of the missing DLL because the Windows API does not return this information making this error hard to diagnose. To resolve this error and determine which DLL is not found, you need to find the list of dependent DLLs and determine which one is not found using Windows debugging and tracing tools.,Windows only: this function is probably the worst-named thing in ctypes. It creates an instance of OSError. If code is not specified, GetLastError is called to determine the error code. If descr is not specified, FormatError() is called to get a textual description of the error.,Windows only: return the filename of the VC runtime library used by Python, and by the extension modules. If the name of the library cannot be determined, None is returned.,This is nice and fine, but how would one access the additional elements contained in this array? Since the type still only knows about 4 elements, we get errors accessing other elements:

byref(obj, offset) corresponds to this C code:

(((char * ) & obj) + offset)

It is possible to define the _fields_ class variable after the class statement that defines the Structure subclass, this allows creating data types that directly or indirectly reference themselves:

class List(Structure):
List._fields_ = [("pnext", POINTER(List)),

Here is an example type (Windows):

class _U(Union):
   _fields_ = [("lptdesc", POINTER(TYPEDESC)),
      ("lpadesc", POINTER(ARRAYDESC)),
      ("hreftype", HREFTYPE)

class TYPEDESC(Structure):
   _anonymous_ = ("u", )
_fields_ = [("u", _U),
   ("vt", VARTYPE)

The TYPEDESC structure describes a COM data type, the vt field specifies which one of the union fields is valid. Since the u field is defined as anonymous field, it is now possible to access the members directly off the TYPEDESC instance. td.lptdesc and td.u.lptdesc are equivalent, but the former is faster since it does not need to create a temporary union instance:

td.vt = VT_PTR
td.lptdesc = POINTER(some_type)
td.u.lptdesc = POINTER(some_type)

Suggestion : 4

Added optional line numbers for IDLE editor windows. Windows open without line numbers unless set otherwise in the General tab of the configuration dialog. Line numbers for an existing window are shown and hidden in the Options menu. (Contributed by Tal Einat and Saimadhav Heblikar in bpo-17535.),Added a force keyword argument to logging.basicConfig() When set to true, any existing handlers attached to the root logger are removed and closed before carrying out the configuration specified by the other arguments.,Another motivating use case arises in list comprehensions where a value computed in a filtering condition is also needed in the expression body:,The PEP 587 adds a new C API to configure the Python Initialization providing finer control on the whole configuration and better error reporting.

if (n: = len(a)) > 10:
   print(f "List is too long ({n} elements, expected <= 10)")
discount = 0.0
if (mo: = '(\d+)% discount', advertisement)):
   discount = float( / 100.0
# Loop over fixed length blocks
while (block: = != '':
[clean_name.title() for name in names
   if (clean_name: = normalize('NFC', name)) in allowed_names
def f(a, b, /, c, d, *, e, f):
      print(a, b, c, d, e, f)
f(10, 20, 30, d = 40, e = 50, f = 60)