Can I prevent a C++ dll from loading in Python Ctypes?
<p>I'd like to know if it's possible prevent or allow a dll to be loaded by python ctypes, based on whether a condition is true <strong>from within the dll.</strong></p>

<p><em>Some background:</em></p>

<p>My application uses various calculation algorithms, which I prototyped in Python, and then reimplemented in C++ for a speed boost. I still use Python for the application "glue" and GUI. I'm accessing the functions in the dll using a ctypes wrapper. </p>

<p>I now need to secure the software, so that it will only run if a security dongle is present. The open nature of Python makes this difficult, so I'd like to be able to stop a python script loading the dll unless a function which checks the dongle is present returns True.</p>

<p>Example Python wrapper:</p>

<pre><code>from ctypes import cdll, c_int , c_float, c_bool

lib = cdll.LoadLibrary('my.dll')

cpp_sum = lib.sum
cpp_sum.argtypes = [c_int,c_int]
cpp_sum.restype = c_int

def wrapped_sum(value_1,value_2):
    return cpp_sum(value_1,value_2)
</code></pre>

<p>And the code for the my.dll:</p>

<pre><code>#include "stdafx.h"
#include &lt;cmath&gt;

#define DLLEXPORT extern "C" __declspec(dllexport)

DLLEXPORT int sum(int a, int b) 
    {return a + b;}

//pseudo dongle code:
bool is_dongle_present(){
    if dongle present return true
    else return false
</code></pre>

<p>Ideally the dll would fail to load if dongle_is_present returned false. Can anyone help?
Please tell me if this question is unclear!</p>

<p>Many thanks</p>

<p>Add <code>DllMain</code> function to your library.</p>

<blockquote>
  <p>An optional entry point into a dynamic-link library (DLL). When the
  system starts or terminates a process or thread, it calls the
  entry-point function for each loaded DLL using the first thread of the
  process. The system also calls the entry-point function for a DLL when
  it is loaded or unloaded using the LoadLibrary and FreeLibrary
  functions. </p>
</blockquote>

<p>You could prevent dll load by returning <code>FALSE</code> on <code>DLL_PROCESS_ATTACH</code>: </p>

<blockquote>
  <p>When the system calls the DllMain function with
  the DLL_PROCESS_ATTACH value, the function returns TRUE if it succeeds
  or FALSE if initialization fails. If the return value is FALSE when
  DllMain is called because the process uses the LoadLibrary function,
  LoadLibrary returns NULL. (The system immediately calls your
  entry-point function with DLL_PROCESS_DETACH and unloads the DLL.) If
  the return value is FALSE when DllMain is called during process
  initialization, the process terminates with an error</p>
</blockquote>

<p>See <a href="https://msdn.microsoft.com/ru-ru/library/windows/desktop/ms682583(v=vs.85).aspx" rel="nofollow">DllMain MSDN entry</a> for the additional information.</p>

python c++ c dll ctypes