1

I'm trying to export a Class within a DLL and use it in Python. So lets say my class is called MyClass, and to use it I need to make an instance with a method called getupdate() which looks like this :

MyClass*    MyClass::getupdate()
{
    if(update==NULL)                    
    {
        update  =   new MyClass();  
    }           
    return update;
}

So after compiling the dll, I load it in a Python script using ctypes module, like this :

from ctypes import *

win = WinDLL('MyDLL')

And here I don't know how to create an instance of MyClass like we can do simply in C++ :

MyClass* update;
update  =   MyClass::getupdate();

I need to have a pointer to MyClass in Python and access the rest of methods within this pointer.

Thank you in advance for you help.

M.Moncif
  • 11
  • 4
  • It's ctypes, not cpptypes. First [create a C API](http://stackoverflow.com/q/2045774/205580) for your C++ classes. Once you have the C API working and tested, then work on creating the ctypes bindings. – Eryk Sun Apr 05 '16 at 12:56
  • ctypes not work with c++ classes - http://stackoverflow.com/questions/1615813/how-to-use-c-classes-with-ctypes – AndreyT Apr 05 '16 at 12:56
  • As examples in these links show, don't forget about exception handling to avoid leaking C++ exceptions that should be handled as error codes. Note that if a Windows DLL is compiled with MSVC, C++ exceptions will use Windows exceptions. These will be caught by the ctypes structured exception handler, but that's not cross-platform and not very useful. Just catch and turn non-critical exceptions into error codes. – Eryk Sun Apr 05 '16 at 12:59
  • Okey guys, actually all what I wanted is to use the methods of this class, so I made a *.def file where I mentioned all the class methods (to avoid name mangling in c++). So now i'm able to call each method directly. So to sum up, I cannot have a pointer to MyClass using ctypes even if I can call all the methods on it directly ? – M.Moncif Apr 05 '16 at 13:14
  • A C++ instance method has an implicit `this` reference, but ctypes doesn't have a `thiscall` for calling instance methods in a 32-bit process. – Eryk Sun Apr 05 '16 at 13:20
  • Is there a way then to export classes in DLL and use them in Python without creating a C API ? – M.Moncif Apr 05 '16 at 14:08
  • Not via ctypes, but you can use [Cython](http://docs.cython.org/src/userguide/wrapping_CPlusPlus.html) if compiling a Python extension module is acceptable. – Eryk Sun Apr 05 '16 at 14:15
  • Ok i'll see what I can do with Cython. Thanks a lot @eryksun. – M.Moncif Apr 05 '16 at 15:18

0 Answers0