[issue38258] ctypes ignores when a DLL function is called with too many arguments

Sebastian Ernst report at bugs.python.org
Tue Sep 24 06:42:06 EDT 2019


Sebastian Ernst <ernst at pleiszenburg.de> added the comment:

Thanks a lot for the clarification, Eryk. I did not notice that it was deprecated behavior.

For the "too many arguments" case I guess this is not an issue. However, just for the symmetry of things, I also looked at calling a function with TOO FEW arguments. 

```C
int16_t __stdcall __declspec(dllimport) mul_ints(
	int16_t a,
	int16_t b
	)
{
	return a * b;
}
```

```python
def test_error_callargs_unconfigured_too_few_args():

	dll = ctypes.windll.LoadLibrary('tests/demo_dll.dll')
	mul_ints = dll.mul_ints

	with pytest.raises(ValueError):
		a = mul_ints(7)
```

As expected after your explanation, also no error in CPython 3.8 (i.e. the test fails, while is passes on CPython <= 3.7). If I run this manually, I even get a "result":

```python
>>> dll = ctypes.windll.LoadLibrary('tests/demo_dll.dll')
>>> mul_ints = dll.mul_ints
>>> a = mul_ints(7)
>>> a
445564 # !
>>> 445564/7 # Just looking at where this result is coming from ...
63652.0
```

Re-starting Python (3.8) and (intentionally) misconfiguring the function interestingly also does not change the result:

```python
>>> dll = ctypes.windll.LoadLibrary('tests/demo_dll.dll')
>>> mul_ints = dll.mul_ints
>>> mul_ints.argtypes = (ctypes.c_int16,)
>>> a = mul_ints(7)                                      
>>> a
445564 # Apparently, this is deterministic?!?
```

Just out of curiosity, where is this data coming from?

This ONLY way to prevent things like this to happen is to actually correctly configure the function:

```python
>>> dll = ctypes.windll.LoadLibrary('tests/demo_dll.dll')
>>> mul_ints = dll.mul_ints
>>> mul_ints.argtypes = (ctypes.c_int16, ctypes.c_int16)
>>> mul_ints(7)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: this function takes 2 arguments (1 given)
```

This should very CLEARLY be mentioned in the documentation ...

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue38258>
_______________________________________


More information about the Python-bugs-list mailing list