Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use C++ class in Python?

Tags:

c++

python

class

I have implemented a class in C++. I want to use it with Python. Please suggest step by step method and elaborate each step. Somthing like this...

class Test{
     private:
        int n;
     public:
        Test(int k){
            n=k;
        }
        void setInt(int k){
            n = k; 
        }
        int getInt(){
            return n;
        }
};

Now, in Python

>>> T1 = Test(12)
>>> T1.getInt()
12
>>> T1.setInt(32)
>>> T1.getInt()
32

Please suggest.How can I do this ? NOTE: I would like to know manual way to do that. I don't want any third party library dependency.

like image 528
Pratik Deoghare Avatar asked Mar 02 '09 14:03

Pratik Deoghare


People also ask

Can Python interact with C?

In general, already-written C code will require no modifications to be used by Python. The only work we need to do to integrate C code in Python is on Python's side. The steps for interfacing Python with C using Ctypes.

How do I connect Python to C?

The rawest, simplest way is to use the Python C API and write a wrapper for your C library which can be called from Python. This ties your module to CPython. The second way is to use ctypes which is an FFI for Python that allows you to load and call functions in C libraries directly.


2 Answers

Look into Boost.Python. It's a library to write python modules with C++.

Also look into SWIG which can also handle modules for other scripting languages. I've used it in the past to write modules for my class and use them within python. Works great.

You can do it manually by using the Python/C API, writing the interface yourself. It's pretty lowlevel, but you will gain a lot of additional knowledge of how Python works behind the scene (And you will need it when you use SWIG anyway).

like image 139
Johannes Schaub - litb Avatar answered Oct 10 '22 08:10

Johannes Schaub - litb


ctypes is good. It is really easy to use, and it comes standard with Python. Unfortunately it can only talk to shared libraries (Unix) or DLLs (Windows) that have a C-style interface, which means you can't directly interface to a C++ object. But you could use a handle system where a handle refers to a particular object.

>>> getInt(h)
12

I think that is simple, easy to understand, and doesn't require extra libraries.

like image 26
dan-gph Avatar answered Oct 10 '22 08:10

dan-gph