注册 登录
编程论坛 Python论坛

python c++混编

编程小白一号 发布于 2022-10-16 14:41, 912 次点击
有人懂python 和c++混编吗,想请教一些问题
2 回复
#2
Rocket_Pro2022-12-18 09:09
#include <python.h>
using namespace std;
int main(){
    ……
}
#3
东海ECS2023-01-29 14:48
Python调用C++类
由于C++支持函数重载,在g++以C++方式编译时编译器会给函数的名称附加上额外的信息,这样ctypes模块就会找不到g++编译生成的函数。因此,要让g++按照C语言的方式编译才可以找到生成的函数名。让编译器以C语言的方式编译就要在代码中使用extern关键字将代码包裹起来。
文件名:cpp_called.cpp
程序代码:

//c++
//Python调用c++(类)动态链接库
#include &lt;iostream&gt;
using namespace std;

 
class TestLib
{<!-- -->
    public:
        void display();
        void display(int a);
};
void TestLib::display() {<!-- -->
    cout&lt;&lt;"First display"&lt;&lt;endl;
}

 
void TestLib::display(int a) {<!-- -->
    cout&lt;&lt;"Second display:"&lt;&lt;a&lt;&lt;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
生成libpycallcpp.so,在Python中调用。
程序代码:

import ctypes
dll = ctypes.cdll.LoadLibrary
lib = dll('./libpycallcpp.so') #刚刚生成的库文件的路径
lib.display()
lib.display_int(0)

结果:
First display
Second display:0
1