Take the 2-minute tour ×

I am trying to use a C++ library in my python app. I can load the dll in python but could not find any solution on how to create an instance of a class that is inside that c++ dll and invoke methods on that onject.

Following is what I did and want

C++ code inside My.dll

class MyClass
    MyMethod(int param);

Python code

from ctypes import *
myDll = windll.LoadLibrary("My.dll")

I want to do the following

myClassInstance = myDll.InstantiateMyClass()
share|improve this question
You should take a look at Boost::Python –  Fábio Diniz Aug 25 '11 at 19:52
You can't even do this mixing different C++ compilers, nevermind a different language. Listen to @CatPlusPlus and write a full-blown Python extension with Python types. –  Ben Voigt Aug 25 '11 at 20:31

2 Answers 2

While it might be possible with ctypes, it certainly won't be as straightforward as that. It'll be much easier to use e.g. Boost.Python or Cython to create a proper CPython extension that exposes that class as a Python type.

share|improve this answer

Loading a C++ dll with Ctypes is dangerous and has some strong limitations. The exported function name is not the same as you declared, unless you declared the function in C++ as 'extern "C"'. This is only possible for pure functions, not for member functions. The C++ compiler does something called "name mangling", see http://en.wikipedia.org/wiki/Name_mangling#Name_mangling_in_C.2B.2B.

I suggest two solutions:

  1. You write some C++ code with pure functions, declared as 'extern "C"', which expose the functionality you need.
  2. I really recommend using Cython http://cython.org/, especially http://docs.cython.org/src/userguide/wrapping_CPlusPlus.html should help you. I used it a lot, and for me it is the best way to wrap C++ code to Python.


I tried boost python some times but found it hard to use. It has its own build system which you have to learn, the compiling process is very very slow, and due to the template syntax the code gets hard to read. It thing the context behind boost python is very cool, but in my opinion it is hard to use.

I also tried SIP and SWIG which I did not feel very comfortable with.

I really recommend to use Cython.

share|improve this answer
did you mean "python" in the first line? i am confused why you say cython is dangerous and limited, then recommend it in (2). (i know nothing about this...) –  andrew cooke Aug 25 '11 at 23:25
fixed it. now it is ctypes. –  rocksportrocker Aug 26 '11 at 8:13

Your Answer


