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 <string>
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 <windows.i>
%include <std_string.i>
%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 <Python.h>

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

posted @   Ldlchina  阅读(9880)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示