CMakeLists.txt
Project (XXX) add_library (xxx SHARED xxx.cpp) add_executable (yyy yyy.cpp) target_link_libraries (yyy XXX)
Xxx.h
#ifndef Xxx_xxx_h#defineXxx_xxx_h#endif#pragmaOnce#ifdef Build_xxx_dll#defineIo_xxx_dll __declspec (export)#else#defineIo_xxx_dll __declspec (import)#endifextern "C"{Io_xxx_dllvoidHellovoid); Io_xxx_dllDoubleSumDoubleADoubleb);}
Xxx.cpp
#defineBuild_xxx_dll#include"xxx.h"#include<iostream>using namespaceStd;io_xxx_dllvoidHellovoid) {cout<<"Hello from dll!\n"<<Endl;} Io_xxx_dllDoubleSumDoubleADoubleb) {cout<<"The sum of"<<a<<" and"<<b<<"is :"<<a + b<<Endl; returnA +b;}
Yyy.cpp
#include <windows.h>#include<iostream>using namespacestd;intMain () {hinstance h= LoadLibrary ("c:\\users\\perelman\\. Clion2016.1\\system\\cmake\\generated\\xxx-4d5c076f\\4d5c076f\\debug\\libxxx.dll"); typedefvoid(*P0) (void); P0 Hello= (p0) GetProcAddress (H,"Hello"); cout<<"Run hello:\n"<<Endl; Hello (); typedefDouble(*P1) (Double,Double); P1 sum= (p1) GetProcAddress (H,"sum"); cout<<"Run sum:\n"<<Endl; SUM (10.0,12.0); FreeLibrary (h); return 0;}
yyy.py
ImportcTYPES#Note One, note the 64bit 32bit problem if a 193 error occurs:%1 is not a valid WIN32 application, see the compiler replaced by 64bit to 32bit#note Two, because the DLL is CDECL interface (such as extern "C" __declspec (dllimport)), so Python with cTYPES. Cdll Interfaceh = ctypes. Cdll ('c:\\users\\perelman\\. Clion2016.1\\system\\cmake\\generated\\xxx-4d5c076f\\4d5c076f\\debug\\libxxx.dll') H.hello ()#Note that the data in Python has to be ctypes processed .#Specify parameter formatH.sum.argtypes =(ctypes.c_double, ctypes.c_double)#indicates the return formatH.sum.restype =ctypes.c_doublePrint(H.sum (10.1, 3))
CMake An example of compiling C + + DLLs (update 2: Adding Python call methods)