Python与C++联合编程

白柒 / 2024-01-15 / 原文

C++ 代码

# 编译指令
# gcc -o test.so -shared -fPIC test.c
g++ -o test.so -shared -fPIC test.cc #for c++
#include <iostream>
using namespace std;

extern "C"{ // for C++ 
int foo(int a, int b){
    cout<<"a: "<<a<<" b: "<<b<<endl;
    return a+b;
}
}

main.py

import ctypes

if __name__ == "__main__":
    loader = ctypes.cdll.LoadLibrary
    lib = loader("./test.so")
    r = lib.foo(1, 2)
    print(r)