c++和python有联系吗_Python和C++交互

关键字:Python 2.7,VS 2010,swig

OS:Win8.1 with update。

1.下载swig:http://www.swig.org/download.html

2.将swig的路径添加到环境变量Path,例如set path=C:\swigwin-3.0.2。

3.用VS创建一个win32 console application名为MyApp并生成解决方案,编译生成MyApp.exe。

111701186716537.jpg

4.在MyApp解决方案里面新建一个win32 dll带导出符号项目名为MyDll,编译生成MyDll.dll。

111701337969390.jpg

5.在MyApp解决方案里面新建一个win32 dll空项目名为MyPython。

111705424053677.jpg

6.修改项目依赖关系。MyApp依赖于MyDll,MyPython依赖于MyDll。

7.修改CMyDll类的实现如下:

MyDll.h

#pragma once#include

using namespacestd;

#ifdef MYDLL_EXPORTS#define MYDLL_API __declspec(dllexport)

#else

#define MYDLL_API __declspec(dllimport)

#endif

//This class is exported from the MyDll.dll

classMYDLL_API CMyDll {public:

CMyDll(void);virtual ~CMyDll() {}string SayHello(stringname);double add(double i, doublej);virtual stringlocation();

};

MyDll.cpp

#include "stdafx.h"#include"MyDll.h"CMyDll::CMyDll()

{return;

}string CMyDll::SayHello(stringname)

{return "Hello" + name + ". I'm from" + location() + ".";

}double CMyDll::add(double i, doublej)

{return i +j;

}stringCMyDll::location()

{return "C++";

}

8.在MyPython项目里添加接口文件MyPython.i。

%module(directors="1") MyPython

%{

#include "../MyDll/MyDll.h"

%}

%feature("director") CMyDll;

%include

%include

%include "../MyDll/MyDll.h"

9.在MyPython.i的属性设置里面设置Custom Build Tool。

111705075939706.jpg

10.编译MyPython.i生成MyPython.py和MyPython_wrap.cxx,把MyPython_wrap.cxx添加到工程MyPython,并设置工程如下,Build工程MyPython生成_MyPython.pyd.

111702352802209.jpg

111703234832300.jpg

111703466551248.jpg

111704123122451.jpg

11.添加TestMyPython.py如下,在_MyPython.pyd的文件夹目录下运行TestMyPython.py.

importMyPythonimportos

o=MyPython.CMyDll()print(o.SayHello("World"))classMyPyDll(MyPython.CMyDll):def __init__(self):

MyPython.CMyDll.__init__(self)deflocation(self):return "Python"o1=MyPyDll();print(o1.SayHello("World"))

os.system("pause")

运行结果如下:

Hello World. I'm from C++.

Hello World. I'm from Python.

Press any key to continue . . .

12.Run python in MyApp。

修改MyApp的工程属性,添加python头文件的文件夹,和lib文件的文件夹。

修改MyApp.cpp的代码如下:

#include "stdafx.h"#include

int _tmain(int argc, _TCHAR*argv[])

{

Py_Initialize();

PyObject* pModule = PyImport_ImportModule("TestMyPython");

Py_Finalize();return 0;

}

编译运行MyApp.exe,结果如下:

Hello World. I'm from C++.

Hello World. I'm from Python.

Press any key to continue . . .

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值