【C++】Python调用C++简单实现

发布于:2022-10-21 ⋅ 阅读:(635) ⋅ 点赞:(0)

参考这位博主的实现。

很多情况下,我们需要用Python调用C++的接口,但在实现中遇到好多问题,在此记录一下:

文章目录

Windows平台

创建好相关文件,下载了MinGW C++编译器,生成链接库.so后,运行Python程序总是提示错误,初步断定是32位和64位的问题,网上的解决方法都不适用,待解决。

在这里插入图片描述

Linux平台

将代码都转移到Linux平台后,运行不报错了。

先创建cpp_called.cpp

#include <iostream>
using namespace std;
 
class TestLib
{
    public:
        void display();
        void display(int a);
};
void TestLib::display() {
    cout<<"First display"<<endl;
}
 
void TestLib::display(int a) {
    cout<<"Second display:"<<a<<endl;
}
extern "C" {
    TestLib obj;
    void display() {
        obj.display();
      }
    void display_int(int a) {
        obj.display(a);
      }
}

执行以下命令编译动态链接库:

g++ -o libpycallcpp.so -shared -fPIC cpp_called.cpp

编译参数说明
-fPIC:无关目标平台,适用于动态连接;
-L path:表示在path目录中搜索库文件,如-L.表示在当前目录;(先不用)
-I path:表示在path目录中搜索头文件;(先不用)
-o file:制定输出文件为file;
-shared:生成一个共享库文件;

然后创建py_call_c.py:

import ctypes
dll = ctypes.cdll.LoadLibrary
lib = dll('./libpycallcpp.so')
lib.display()
lib.display_int(123)

最后在命令行执行:

python3 py_call_c.py

结果如下:

在这里插入图片描述

以上。


网站公告

今日签到

点亮在社区的每一天
去签到