赵小黑 发表于 2015-4-22 10:30:32

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。

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

  5.在MyApp解决方案里面新建一个win32 dll空项目名为MyPython。
  
  6.修改项目依赖关系。MyApp依赖于MyDll,MyPython依赖于MyDll。
  7.修改CMyDll类的实现如下:
  MyDll.h



#pragma once
#include
using namespace std;

#ifdef MYDLL_EXPORTS
#define MYDLL_API __declspec(dllexport)
#else
#define MYDLL_API __declspec(dllimport)
#endif
// This class is exported from the MyDll.dll
class MYDLL_API CMyDll {
public:
CMyDll(void);
virtual ~CMyDll() {}
string SayHello(string name);
double add(double i, double j);
virtual string location();
};
  MyDll.cpp



#include "stdafx.h"
#include "MyDll.h"

CMyDll::CMyDll()
{
return;
}
string CMyDll::SayHello(string name)
{
return "Hello " + name + ". I'm from " + location() + ".";
}
double CMyDll::add(double i, double j)
{
return i + j;
}
string CMyDll::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。

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




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



import MyPython
import os
o = MyPython.CMyDll()
print(o.SayHello("World"))
class MyPyDll(MyPython.CMyDll):
def __init__(self):
MyPython.CMyDll.__init__(self)
def location(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 . . .
  
  源代码下载:https://github.com/ldlchina/CppPythonSwig/tree/839e3e50993d209c83c4b5c587369c98a8f05d5a
页: [1]
查看完整版本: Python和C++交互