-1

I'm sorry if the question seems repeated many times here but I spent the whole day without finding a clear answer.

I'm working under Visual Studio 2010 and i'm trying to load a class defined in a DLL into Python. I saw that there's no way to do this without making a C++ wrapper (using eventually SWIG or Boost.Python). I'm not a C++ programmer and I couldn't find an easy and clear tutorial to start with, I will be grateful if you could give me a simple one.

Also, my class uses the singleton pattern that restricts its instantiation to one object like this :

MyClass*    MyClass::getInstance()
{
    if(instance==NULL)                  
        instance    =   new MyClass();      

    return instance;
}

So I need to know how I can deal with this in my Python script so that I can create an instance of MyClass and access all its methods.

Thanks guys.

M.Moncif
  • 11
  • 4
  • http://www.boost.org/doc/libs/1_42_0/libs/python/doc/tutorial/doc/html/index.html – neohope Apr 06 '16 at 15:40
  • You've told us almost nothing about your scenario other than the one comment about singletons. What exactly are you struggling with that isn't already described much better than I could in http://www.swig.org/Doc3.0/SWIGPlus.html ? – Flexo Apr 06 '16 at 21:11
  • Actually that part about singletons that I posted is what I need the most. I don't know how to handle pointers in Python. For example, I'd do something like : _import MyDLL_ _instance = MyDLL.getInstance()_ _instance.someMethod()_ But I'm not sure it will be that simple.. – M.Moncif Apr 07 '16 at 07:29

1 Answers1

0

After finding the solution to my problem, I come back to answer my question to whom it might help.

I used SWIG to make the C++ wrapper. So I defined the module interface something like :

%module MyClass
    %{
    #include    "MyClass.h"
    %}
    %include <windows.i>   //if you're using __declspec(dllexport) to export dll
    %include "MyClass.h"

Then compiled it directly with :

    >swig -c++ -python MyClass.i

And that generates two files : MyClass.py and MyClass_wrap.cxx.

I then included the MyClass_wrap.cxx file to my project in Visual Studio and made these changes on my project properties :

Configuration properties > General > Target Name : _MyClass Target Extension : .pyd

C/C++ > General > Additional Include Directories : /path/to/Python/include

Linker > Additional Library Directories : //path/to/Python/libs

And then compiled the project to generate _MyClass.pyd.

In my Python script, it is as simple as the following :

import MyClass
instance = MyClass.MyClass.getInstance()
#and then use all MyClass methods via instance, ex: instance.SomeMethod()

That's all. SWIG does all the work to handle the reference returned by getInstance().

M.Moncif
  • 11
  • 4