python调用C++中的函数(最简明教程)

C++的函数需要用extern描述才能被Python调用。先建一个名为ct.cpp的c++文件,如下:

#include<iostream>
#include<string>
using namespace std;
extern "C"{
int hehe(){
        cout<<"hehe"<<endl;
        return 0;
}
}

在Linux环境下编译:

g++ -o ct.so -shared -fPIC ct.cpp

根据上面的编译命令,就可以在同目录下得到名为ct.so的文件了 ,这就是可以被python直接调用的。再来看看python调用的代码:

import ctypes
ll = ctypes.cdll.LoadLibrary
lib = ll('./ct.so')
lib.hehe()

输出为:

hehe

 这样就成功实用python调用了C++的函数。

猜你喜欢

转载自blog.csdn.net/leviopku/article/details/83824625