如何在Python中使用C ++类? [英] How can I use C++ class in Python?

查看:165
本文介绍了如何在Python中使用C ++类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++中实现了一个类。我想使用它与Python。
请逐步建议并详细说明每个步骤。
像这样...

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;
        }
};

现在,在Python中

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.

推荐答案

查看 Boost.Python 。这是一个用C ++编写python模块的库。

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

还要查看 SWIG ,也可以处理其他脚本语言的模块。我使用它在过去为我的类编写模块,并在python中使用它们。非常棒。

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.

您可以使用 Python / C API ,自己编写界面。这是相当低的水平,但你会获得许多额外的知识,如何Python的背后的场景(而且你会需要它,当你使用SWIG反正)。

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).

这篇关于如何在Python中使用C ++类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆