1、主要是通过将.cpp文件转为.so文件,才给python利用。.so文件又称(share object)
$ g++ -o lib.so -shared -fPIC name.cpp
譬如:
main.h
#ifndef MAIN_H
#define MAIN_H
#define HELLO "hello world"
#endif
main.cpp
#include <iostream>
#include "main.h"
using namespace std;
class TestLib
{
public:
void display();
void display(int a);
};
void TestLib::display()
{
cout << "First display" << endl;
cout << HELLO << 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);
}
}
hello.py
from ctypes import cdll
so = cdll.LoadLibrary
lib = so("./libmain.so")
lib.display()
a = 100
lib.display_int(a)
print("a : %d"%a)
网友评论